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?
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
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