Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...