Reputation: 364
For example if I have a file like
[email protected], yo@
gmail.com yo@gmail
.com
And I want to replace the string [email protected]
.
If the file had the target string in a single line then we could've just used
sed "s/[email protected]/[email protected]/g" file
So, is it possible for me to catch patters that are spread between multiple line without replacing the \n?
Something like this
[email protected], e@
email.com e@email
.com
Thank you.
Upvotes: 1
Views: 189
Reputation: 58371
This might work for you (GNU sed):
sed -E 'N;s/yo@gmail\.com/[email protected]/g
h;s/(\S+)\n(\S+)/\1\2\n\1/;/yo@gmail\.com/!{g;P;D}
s//\[email protected]/;:a;s/\n(\S)(\S+)\n\S/\1\n\2\n/;ta
s/(.*\n.*)\n/\1/;P;D' file
Append the following line to the pattern space.
Replace all occurrences of matching email address in both the first and second lines.
Make a copy of the pattern space.
Concatenate the last word of the first line with the first word of the second and keep the second line as is. If there is no match with the email address, revert the line, print/delete the first line and repeat.
Otherwise, replace the match and re-insert the newline as of the length of the first word of the second line (deleting the first word of the second line too).
Remove the newline used for scaffolding, print/delete the first line and repeat.
N.B. The lines will not be of the same length as the originals if the replacement string length does not match the matching string length. Also there has been no attempt to break the replacement string in the same relative split if the match and replacement strings are not the same length.
Alternative:
echo $'[email protected]\[email protected]' |
sed -E 'N;s#(.*)\n(.*)#s/\\n\1/\\n\2/g#
:a;\#\\n([^/])(.*)\\n(.)?(.*/g)#{s//\1\\n\2\3\\n\4/;H;ba}
x;s/.//;s#\\n/g$#/g#gm;s#\\n/#/#;s/\./\\./g' |
sed -e 'N' -f - -e 'P;D' file
or:
echo 's/[email protected]/[email protected]/' |
sed -E 'h;s#/#/\\n#g;:a;H;s/\\n([^/])/\1\\n/g;ta;x;s/\\n$//mg;s/\./\\./g' |
sed -zf - /file
N.B. With the last alternative solution, the last sed invocation can be swapped for the first alternative solutions last sed invocation.
Upvotes: 1
Reputation: 103744
You can do this:
tr -d '\n' < file | sed 's/[email protected]/[email protected]/g'
Upvotes: 1