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.


2 Answers 2


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) \$/"


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.


To cut down on the backslashes we shall use the GNU sed with its extended regex mode -E turned ON. Plus, we shall use the back referencing brackets to further cut down on the rhs of the s/// command. Plus, we utilize the dollar inside a character class [...] gets treated as a literal.

sed -Ee "s/([\$]Date)([\$])/\1 $(date) \2/"

Or, Posixly we can do as shown:

sed -e '/\($Date\)\$/ '"s//\1 $(date) \$/"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .