Using sed to replace a string in a specific position

I asked this before, but my problem got more complicated. Heres what I am trying to do:

I'm trying to replace a string at a certain location with another string.

Heres the file I'm trying to change:

\E[0;40m \E[0;40m \E[0;40m \E[0;40m 
\E[0;40m \E[0;40m \E[0;40m \E[0;40m 
\E[0;40m \E[0;40m \E[0;40m \E[0;40m 
\E[0;40m \E[0;40m \E[0;40m \E[0;40m 
\E[0;40m \E[0;40m \E[0;40m \E[0;40m

I want to replace the escape code at the 3rd line, 2nd column with this escape code "\E[5;47m".

Heres what I tried:

sed "3 s/.;40m /5;47m /2" inputfile

The code above works, but heres the issue:

I want to be able to make sed replace any escape code with "\E[5;47m", but the sed program only detects the escape code "\E[0;40m". How can I make sed detect every escape code including "\E[0;40m"?

Like detect "\E[3;43m"? Does sed have an option like "3 s/.*;m /5;47m /2", the "" asterisk detects numbers 0-9?

for any escape code at 3rd line, 2nd column..

# sed '3s|\E\[[0-9][0-9]*;[0-9][0-9]*m|E[5;47m|2' infile
\E[0;40m \E[0;40m \E[0;40m \E[0;40m
\E[0;40m \E[0;40m \E[0;40m \E[0;40m
\E[0;40m \E[5;47m \E[0;40m \E[0;40m
\E[0;40m \E[0;40m \E[0;40m \E[0;40m
\E[0;40m \E[0;40m \E[0;40m \E[0;40m

regards
ygemici

1 Like
sed '3s/[^ ]*/\\E[5;47m/2' infile
sed "3s/[^ ]*/\\\E[5;47m/2" infile
1 Like

This is the best forum of all time :smiley:

Both solutions worked. Thank you.