0

I'm trying to get the current date as month/day (i.e., 6/18), printed into a .cfg file (using sed because I need a specific line changed). However, when running the bash, the date is correct in the output but when checking the file it's printing the command not the date. Any suggestions?

sed -i -- 's/^example=.*/example="$(date)"/g' /path/to/config.cfg

Also, date is just printing the full date (Thu June 18 19:34:14 EDT 2020), I just need the month/day.

Thank you in advance!!!

1 Answer 1

1

The shell never expands anything inside a single quoted string.

You will have to use a double quoted string for your sed expression:

sed -i "s,^\(example=\).*,\1$(date +%m/%d)," /path/to/config.cfg

Alternatively, use two single quoted strings with the command substitution in double quotes between them:

sed -i 's,^\(example=\).*,\1'"$(date +%m/%d)"',' /path/to/config.cfg

Alternatively, let date output the sed expression:

sed -i "$(date +'s,^\(example=\).*,\1%m/%d,')" /path/to/config.cfg

(but this looks a bit awkward).

I turned the expression a bit shorter by means of a back-reference for the example= text. I'm using , as the delimiter for the s/// command in sed because we're dealing with a string in the replacement part that contains a / character (the alternative would have been to use %m\\/%d as the format string with date to generate an escaped / character).

Note that the double quotes around the command substitution are not needed in the first variation of the command above as the whole sed expression is quoted. Also, the /g at the end of the s/// command is not needed as you can't expect the pattern to match more than once, since it's anchored to the start of the line. I've also removed the -- that you used. Some sed implementations would almost certainly have used that string as the backup suffix, i.e. as the option-argument to the -i option (e.g. sed on macOS).

I'm using date +%m/%d to generate the wanted date format. This would generate 06/19 for today's date. Would you not want zero-filled numbers for the day, use %e in place of %d (see man strftime). There does not appear to be a standard format for getting the month without zero filling the number, but if you use GNU date you may use the non-standard %-m format (i.e. date +%-m/%e, see man date).

1
  • Thank you so much @Kusalananda. Not only did you solve my problem, you also educated me in a clear/understandable manner. I greatly appreciate it. Jun 19, 2020 at 0:11

You must log in to answer this question.

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