Skip to content
Advertisement

Converting date format in bash

I have similar different file of the format backup_2016-26-10_16-30-00 is it possible to rename using bash script to backup_26-10-2016_16:30:00 for all files. Kindly suggest some method to fix this.

Original file:

backup_2016-30-10_12-00-00

Expected output:

backup_30-10-2016_12:00:00

Advertisement

Answer

To perform only the name transformation, you can use awk:

echo 'backup_2016-30-10_12-00-00' |
  awk -F'[_-]' '{ print $1 "_" $3 "-" $4 "-" $2 "_" $5 ":" $6 ":" $7 }'

As fedorqui points out in a comment, awk‘s printf function may be tidier in this case:

echo 'backup_2016-30-10_12-00-00' |
  awk -F'[_-]' '{ printf "%s_%s-%s-%s_%s:%s:%sn", $1,$3,$4,$2,$5,$6,$7 }'

That said, your specific Linux distro may come with a rename tool that allows you to do the same while performing actual file renaming.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement