I want to replace a string found in a file with another string, but both have a special character (in this example it is a .
char) e.g 1.0
and 2.0
.
So this is the command currently used:
sed -i 's/1\.0/2\.0/g' /home/user1/file1.txt
What if 1.0
and 2.0
were saved in variables $i
and $j
? where i
has the value 1.0
and j
has the value 2.0
, how can I still replace i
with j
?
Best Answer
You can just use
sed
to do the fixup for you:So this
s///
ubstitution will escape any/all BRE metacharacters in input:...by prefixing each with a backslash. The first
sed
then saves a copy of the first line -$i
- inH
old space by prepending a\n
ewline character to it. The$i
line is thend
eleted because it is!
not the$
last. The next line - the$j
line - is also the last, and after it gets the same treatment as the first, it is notd
eleted. Instead, it ex
changes the hold and pattern buffers and operates on the concatenated results. At this point pattern space looks like:...so we
y///
translate all\n
ewlines for/
slashes,s///
ubstitute.*
all of pattern-space for&
itself plus a prependeds
and an appended/g
which gets us:This is then autoprinted to the second
sed
which is reading stdin - or-f -
- as its script. When the firstsed
is finished and closes the pipe between them, the secondsed
starts applying......to every line in its named input file - which is here
/path/to/infile
.I wrote your file like this:
Which got me a file like...
I then wrote a different version of your script like:
Which uses the shell only to generate the strings, but allows
sed
to do all of the data processing. Notice that though twosed
s are called each is only ever called once.When I run it the results are:
The lines beginning with
#
are colored red as I expect you mean them to be.sed
only writes them when as///
ubstitution is successful. The script that the firstsed
writes for the second looks like:Note though that that though it appears the
[
strings are not escaped this is just the effect of my terminal on the output - which winds up eating the char immediately following\033
. When the secondsed
receives the script the input is like\033\[...
but the output iti
nserts to stdout is\033[...