Nelson P Nelson P - 1 month ago 9
Bash Question

Sed command: search for a string & replace 1 character after the string

I am trying to use the

sed
command in a shell script in osx/bash. I am well able to replace some content of
MyFile
using the simplest form of command like below

sed -i -e 's/abc/123/g' MyFile


where MyFile content is
xyzabcdefghijk
. The above command works great to replace
abc
with
123
& makes the output as
xyz123defghijk


But, How do I modify the
sed
command to replace
2
characters after
abc
as well along with
abc
. In clear words, I want to search for a string
abc
in
MyFile
& replace
abc + 2
characters after it with
12345
.


So, if
MyFile
contains,
abcdefghijk
then the output should contain
xyz12345fghijk


Any suggestions please ?

Answer

To change abc and the two characters after abc:

$ sed -e 's/abc../12345/g' MyFile
xyz12345fghijk

In regular expressions, . matches any single character. So, .. matches two characters and abc.. matches abc and any two characters after abc.

To make the change to the file in-place:

sed -i.bak -e 's/abc../12345/g' MyFile
Comments