How do I insert text after two consecutive matches in a file using sed. Is this possible? If it is, how do I do the following?
My file:
abcdef()K
.xyz 1
('I want to add text here')
Note that the .xyz will be same but it can be 1 or 2 or 3 or any other number. But .xyz WILL DEFINIETLY BE under abcdef()K. I want to add text exactly AFTER the .xyz part.
Please do help guys. Thanks.
CodePudding user response:
You can use this perl:
perl -0777 -pE 's/^(abcdef\(\)K\R\.xyz.*\R?)/\1(your text here)\n/mg' file
Or this awk:
awk -v ins="(your text)" '/abcdef()K/{f=1; print; next}
f && /\.xyz.*/{f=0; print; print ins; next}
{f=0; print}' file
CodePudding user response:
If .xyz [0-9] is constant and is always on the line below the first match, then you can append the new line with sed
$ sed '/\.xyz [0-9]*/a New Text' input_file
abcdef()K
.xyz 1
New Text
Otherwise, you can match the first line, add a condition to substitute the match on the second line if the first matched, substitute it for itself, jump to new line and append the new text.
sed '/a.*()K/ {N;s/\.xyz [0-9]*/&\nNew Text/}' input_file
abcdef()K
.xyz 1
New Text
CodePudding user response:
This might work for you (GNU sed):
sed -e '/abcdef()K/!b' -e ':a;n;/\.xyz/!ba' -e 'a new text added' file
If a line does not contain abcdef()K bail out.
Print the current line and fetch the next.
If the current line does not contain .xyz, repeat above.
Otherwise, append new text added to the current line.
sed -e '/abcdef()K/!b' -e ':a' -e 'n' -e '/\.xyz/!ba' -e 'a new text added' file
Or:
cat <<\! | sed -f - file
/abcdef()K/!b
:a
n
/\.xyz/!ba
a new text added
!
