Reputation: 29280
I would like to apply some sed commands to a range of lines. The range is defined by a starting regexp and an ending regexp. Is there a way to use a sub-expression of the first regexp in the second? Example where the starting and ending lines of the range must have the same number of leading tabs:
sed -r '/^(\t*)FOO$/,/^\1BAR$/d' file
Of course, this example does not work.
Upvotes: 0
Views: 683
Reputation: 89584
No you can't use a backreference to a group from one pattern in an other. (in other words, each pattern has its own groups.)
What you can do is to append lines one by one in the pattern space until the pattern matches.
sed -r '/^\t*FOO$/{:a;N;/^(\t*)FOO(\n.*)*\n\1BAR$/d;ba;};' file
details:
/^\t*FOO$/ { # when the first line of the block is found:
:a; # define the label "a"
N; # append the next line to the pattern space
/^(\t*)FOO(\n.*)*\n\1BAR$/d; # delete lines from pattern space
# when the pattern matches
ba; # go to the label "a"
};
Note that d
stops the current command and starts all the command cycle over again with the next line.
Upvotes: 1