How to match multiple addresses in sed?

I want to execute a command sedfor any line that matches either andone or orseveral commands: for example, it sed '50,70/abc/d'will delete all lines in the range 50,70that match /abc/, or a way to do sed -e '10,20s/complicated/regex/' -e '30,40s/complicated/regex/without re-enterings/compicated/regex/

+5
source share
4 answers

logical and

The part andcan be done using curly braces:

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

In addition, braces can be nested in several conditions and.

(The above was tested at GNU sed. BSD sedmay differ in small but disappointing details.)

Logical or

or :

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

    10 20 cr

  • 30,40{b cr;}

    30 40 cr

  • b

    .

  • :cr

    cr

  • s/complicated/regex/

    , cr.

GNU sed :

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

10 20 30 40, GNU:

sed -e '10,20bA;30,40bA;b;:A;s/complicated/regex/;d' file

sed -e '10,20bA' -e '30,40bA' -e 'b;:A;s/complicated/regex/;d' file


bA: :A

b: → script

d:

+2

, sed , - awk, - :

awk 'NR >= 50 && NR <= 70 && /abc/ {next} {print}' inputFile
awk '(NR >= 10 and NR <= 20) || (NR >= 30 && NR <= 40) {
     sub("from-regex", "to-string", $0); print }'
+1

sed is great for simple substitutions on separate lines, but for something else just use awk for clarity, reliability, portability, maintainability, etc.

awk '
(NR>=50 && NR<=70) && /abc/ { next }
(NR>=10 && NR<=20) || (NR>=30 && NR<=40) { sub(/complicated/,"regex") }
{ print }
' file
0
source

All Articles