How to change date format in sed?

e switch in sed substitute applies sh -c to unmatched text as well as evident from this command:

echo 'a 1449158360' | sed -r 's#([0-9]{10})#date -d@\1 "+%Y";#e'
sh: a: command not found 

So even though we are matching only 1449158360 but sh -c is being run on a 1449158360.

Due to absence of non-greedy and lookaheads regex in sed this workaround regex might appear crazy but this is how you can run it for multiple matching input from file as in your question:

sed -r 's#(([^0-9][0-9]{0,9})*)(\b[0-9]{10}\b)(([0-9]{0,9}[^0-9])*)#printf "%s%s%s" "\1" $(date -d@\3 "+%Y") "\4";#ge' file

Basically we are matching <before>10-digits<after> in this regex.

Output:

my timestamp is 2015 but also I wonder what date was 2013.

To clarify the regex used I have created this demo.

By no means this is a generic solution to e mode issue, treat it as a regex based workaround.

Leave a Comment