Skip to content

Instantly share code, notes, and snippets.

@Karneades
Last active January 22, 2021 20:33
Show Gist options
  • Save Karneades/898a0498ac51b559bfdd4258459abf2a to your computer and use it in GitHub Desktop.
Save Karneades/898a0498ac51b559bfdd4258459abf2a to your computer and use it in GitHub Desktop.
Convert unix timestamps to other format using sed and date #shell #bash #zsh #epoc

Convert unix timestamps in a file using sed and date

Replace unix (epoc) timestamp to other format without changing the file, only print the changes

The /e modifier can be dangerous because it runs the resulting string as code. It is basically an eval() wrapped inside a regex engine. Nonetheless, if you know the content of the file, the sed command is one of the shortest to replace unix timestamps in a file.

# default format used by date
$ sed -E 's/([0-9]{10})/echo ""$(date -d @\1)/e' test.txt
Fri Jan 22 14:00:31 2021 my log entry
Fri Jan 22 14:00:32 2021 my log entry
Fri Jan 22 15:24:12 2021 my log entry

# use custom format
$ sed -E 's/([0-9]{10})/echo ""$(date +"%d-%m-%Y %T" -d @\1)/e' test.txt
22-01-2021 14:00:31 my log entry
22-01-2021 14:00:32 my log entry
22-01-2021 15:24:12 my log entry

Using -i the changes are written to the file

$ sed -Ei 's/([0-9]{10})/echo ""$(date +"%d-%m-%Y %T" -d @\1)/e' test.txt
$ cat test.txt
22-01-2021 14:00:31 my log entry
22-01-2021 14:00:32 my log entry
22-01-2021 15:24:12 my log entry

Print current time in epoc

$ date +"%s"

As an example, a test file test.txt is used

$ cat test.txt
1611320431 my log entry
1611320432 my log entry
1611325452 my log entry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment