Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

command line - How do I match multiple addresses in sed?

I want to execute some sed command for any line that matches either the and or or of multiple commands: e.g., sed '50,70/abc/d' would delete all lines in range 50,70 that match /abc/, or a way to do sed -e '10,20s/complicated/regex/' -e '30,40s/complicated/regex/ without having to retype s/compicated/regex/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Logical-and

The and part can be done with braces:

sed '50,70{/abc/d;}'

Further, braces can be nested for multiple and conditions.

(The above was tested under GNU sed. BSD sed may differ in small but frustrating details.)

Logical-or

The or part can be handled with branching:

sed -e '10,20{b cr;}' -e '30,40{b cr;}' -e b -e :cr -e 's/complicated/regex/' file
  • 10,20{b cr;}

    For all lines from 10 through 20, we branch to label cr

  • 30,40{b cr;}

    For all lines from 30 through 40, we branch to label cr

  • b

    For all other lines, we skip the rest of the commands.

  • :cr

    This marks the label cr

  • s/complicated/regex/

    This performs the substitution on lines which branched to cr.

With GNU sed, the syntax for the above can be shortened a bit to:

sed '10,20{b cr}; 30,40{b cr}; b; :cr; s/complicated/regex/' file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...