jb26
jb26

Reputation: 35

replace string with special characters using sed

I have the following string in a file: "dd/mmm/YYYY:HH:MM:SS -0500" and would like it to be replaced with an actual date i.e. "17/Mar/2016:18:14:40 -0500"

I tried using sed, but the following doesn't seem to work

dateTemplate="dd/mmm/YYYY:HH:MM:SS -0500"
actualDate="17/Mar/2016:18:14:40 -0500"
sed -i "s#'$dateTemplate'#'$actualDate'#g" tmp.txt

Any help would be appreciated.

Upvotes: 0

Views: 196

Answers (3)

glenn jackman
glenn jackman

Reputation: 246744

I would automate the process a bit:

dateTemplate="dd/mmm/YYYY:HH:MM:SS -0500"

actualDateTemplate="+$(
    sed '
        s/\<dd\>/%d/g
        s/\<mmm\>/%b/g
        s/\<YYYY\>/%Y/g
        s/\<HH\>/%H/g
        s/\<MM\>/%M/g
        s/\<SS\>/%S/g
        # add more translations here if desired
    ' <<<"$dateTemplate"
)"

actualDate=$(date "$actualDateTemplate")

echo "foo $dateTemplate bar" | sed "s#$dateTemplate#$actualDate#g"
foo 17/Mar/2016:20:22:34 -0500 bar

There's always the danger that the dateTemplate variable will contain the character used as the s/// delimiter, no matter what character you use. This process can be done with string operations in the shell, but that's tedious.

Upvotes: 0

user6064610
user6064610

Reputation:

EDIT: I noticed you were using a different delimiter. I can confirm that Michael Jaros' is a more accurate answer.

You will need to escape the slashes:

dateTemplate="dd/mmm/YYYY:HH:MM:SS -0500"
actualDate="17\/Mar\/2016:18:14:40 -0500"
sed -i "s/$dateTemplate/$actualDate/g" tmp.txt

I tested that working. Let me know if it doesn't!

Upvotes: 0

Michael Jaros
Michael Jaros

Reputation: 4681

Try removing the single quotes(') from the sed program:

dateTemplate="dd/mmm/YYYY:HH:MM:SS -0500"
actualDate="17/Mar/2016:18:14:40 -0500"
sed -i "s#$dateTemplate#$actualDate#g" tmp.txt

Tested with GNU sed version 4.2.1

Before:

1. pre dd/mmm/YYYY:HH:MM:SS -0500 post
2. pre dd/mmm/YYYY:HH:MM:SS -0500 post

After:

1. pre 17/Mar/2016:18:14:40 -0500 post
2. pre 17/Mar/2016:18:14:40 -0500 post

Upvotes: 1

Related Questions