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/
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.
' [^ 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.
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).
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.
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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With