Sed command to replace $Date$ with $Date: 2021-01-06

sed

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

I tried: sed "s/\$Date\$/\$Date $(date) \$/" but it does not work.

Because \$ in double-quotes only tells the shell not to interpret (expand) $, but then there's sed. It gets s/$Date$/$Date … $/ (where denotes what $(date) expanded to) and interprets the second $ as an anchor matching the end of the line. In s/regexp/replacement/ $ is interpreted as the anchor only at the end of regexp. So you need to escape this particular $ also for sed, i.e. you need sed to literally get \$. This can be done with:

sed "s/\$Date\\$/\$Date $(date) \$/"

or

sed "s/\$Date\\\$/\$Date $(date) \$/"

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:

sed 's/$Date\$/$Date '"$(date)"' $/'

Here all $ characters that should get to sed are single-quoted; and the only \ that should get to sed is also single-quoted.

Related Question