Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SED keep pattern in \1 for next block/command

Tags:

sed

I want match a pattern, but replace something else with the matched pattern.

pattern1    X1 X2 X3
pattern2    X4 X5
...

should be transformed into

pattern1-1
pattern1-2
pattern1-3

pattern2-4
pattern2-5

...

I can't just replace 'X' because it is multiple times in a row.

I tried sed -r '/(pattern[0-9])/ { s/X/\n\1/g; }' but this will give me an invalid reference \1 on `s error.

Is there another way to do it?

like image 281
Kolle Avatar asked May 11 '26 21:05

Kolle


1 Answers

This might work for you (GNU sed):

sed -E 's/(\S+)\s+X(\S+)/\1-\2\n\1/;/-/!s/.*//;P;D' file

Use pattern matching to match the first field and another beginning with X. Manipulate to the desired result and then append a newline and the first field again. Print/delete upto and including the first newline and if a line does not match delete, its contents i.e. print a blank line.

If the blank line is not required, use:

sed -E 's/(\S+)\s+X(\S+)/\1-\2\n\1/;/-/P;D' file
like image 166
potong Avatar answered May 14 '26 11:05

potong