Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 1000
iobender Avatar asked Mar 03 '15 06:03

iobender


People also ask

How can address be applied in two different ways in sed command?

A sed command can specify zero, one, or two addresses. An address can be a line number, a line addressing symbol, or a regular expression ( 26.4 ) that describes a pattern. If no address is specified, then the command is applied to each line.

How do you match a character in sed?

' [^ tab ]\+ ' (Here tab stands for a single tab character.) This matches a string of one or more characters, none of which is a space or a tab. Usually this means a word.

Is sed a regex?

The sed command has longlist of supported operations that can be performed to ease the process of editing text files. It allows the users to apply the expressions that are usually used in programming languages; one of the core supported expressions is Regular Expression (regex).

What is line addressing in Linux?

A line address selects a line when the line number is equal to line number counter. The counter runs cumulatively through multiple input files; it is not reset when a new input file is opened. As a special case, the character $ matches the last input line. Context Addresses.


1 Answers

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
like image 105
John1024 Avatar answered Oct 24 '22 22:10

John1024