I need to use a sed
command to search a text file and replace $Date$
with: $Date: 2021-01-06... $
where ...
is the text for the date.
I have a sed
command that will search for Date
and replace it with Date: 2021-01-06...
:
sed "s/Date/Date $(date)/"
but I can't get a sed
command to work to replace $Date$
.
Also, I was able to get a sed
command to replace $Date
using sed "s/\$Date/\$Date $(date)/"
but I can't figure out the syntax to search and replace $Date$
.
I tried:
sed "s/\$Date\$/\$Date $(date) \$/"
but it does not work.
Best Answer
Because
\$
in double-quotes only tells the shell not to interpret (expand)$
, but then there'ssed
. It getss/$Date$/$Date … $/
(where…
denotes what$(date)
expanded to) and interprets the second$
as an anchor matching the end of the line. Ins/regexp/replacement/
$
is interpreted as the anchor only at the end ofregexp
. So you need to escape this particular$
also forsed
, i.e. you needsed
to literally get\$
. This can be done with:or
It works with two or three backslashes because double-quoted
$
before/
does not need to (but may) be escaped, and to get\
you need\\
in double-quotes. This is kinda complicated, therefore consider single-quoting all fragments that don't need to be double-quoted:Here all
$
characters that should get tosed
are single-quoted; and the only\
that should get tosed
is also single-quoted.