2

I have a file that I would like to rename using sed. For simplicity purposes, this is what I am trying to do:

sh-4.3$ echo `date`
Thu 17 Sep 08:29:50 EAT 2015
sh-4.3$ echo `date` | sed 's/`date`/Today/'
Thu 17 Sep 08:29:58 EAT 2015
sh-4.3$ 

I expect it to echo "Today". What's the catch?

Benda
  • 110
  • 3
  • 14
  • 2
    Take a look at [Difference between single and double quotes in bash](http://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash) – Cyrus Sep 17 '15 at 05:34

3 Answers3

3

Inside single-quotes, backticks are not evaluated. Use double-quotes instead:

$ echo `date` | sed "s/`date`/Today/"
Today

For a variety of reasons, backticks are considered archaic. For all POSIX shells, use $(...):

$ echo $(date) | sed "s/$(date)/Today/"
Today

Although it may not be relevant to your larger script, for this simple command, echo is not needed:

$ date | sed "s/$(date)/Today/"
Today

Note that this is fragile. If the seconds happen to tick over between the execution of one and the other date commands, then this substitution will fail.

John1024
  • 109,961
  • 14
  • 137
  • 171
  • Thanks for the pointers. I eventually will not be using the seconds, as am interested only in the D, M and Y parts, like this: `echo $(date +%Y%m%d) | sed "s/$(date +%Y%m%d)/Today/"`. Works fine and thanks for the $(...) pointer too – Benda Sep 17 '15 at 05:58
  • @Benda Glad it helped. – John1024 Sep 17 '15 at 06:02
0
echo `date`

is not the same as

echo 'date'

backticks cause execution of the expression encased within them, single quotes are a plain string.

Since your echo is so simple, echo date would work just as well.

Olipro
  • 3,489
  • 19
  • 25
0

I preconise to also change the separator, date info could have some meta character depending settings

date | sed "s~$( date )~Today~"
NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43