Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date formats in bash

Tags:

date

linux

bash

awk

I have a date in this format: "27 JUN 2011" and I want to convert it to 20110627

Is it possible to do in bash?

like image 732
vehomzzz Avatar asked Jun 28 '11 15:06

vehomzzz


People also ask

How can I change the date format in UNIX?

To format date in YYYY-MM-DD format, use the command date +%F or printf "%(%F)T\n" $EPOCHSECONDS . The %F option is an alias for %Y-%m-%d . This format is the ISO 8601 format.

How do I echo date in bash script?

Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...


1 Answers

#since this was yesterday date -dyesterday +%Y%m%d  #more precise, and more recommended date -d'27 JUN 2011' +%Y%m%d  #assuming this is similar to yesterdays `date` question from you  #http://stackoverflow.com/q/6497525/638649 date -d'last-monday' +%Y%m%d  #going on @seth's comment you could do this DATE="27 jun 2011"; date -d"$DATE" +%Y%m%d  #or a method to read it from stdin read -p "  Get date >> " DATE; printf "  AS YYYYMMDD format >> %s"  `date -d"$DATE" +%Y%m%d`      #which then outputs the following: #Get date >> 27 june 2011    #AS YYYYMMDD format >> 20110627  #if you really want to use awk echo "27 june 2011" | awk '{print "date -d\""$1FS$2FS$3"\" +%Y%m%d"}' | bash  #note | bash just redirects awk's output to the shell to be executed #FS is field separator, in this case you can use $0 to print the line #But this is useful if you have more than one date on a line 

More on Dates

note this only works on GNU date

I have read that:

Solaris version of date, which is unable to support -d can be resolve with replacing sunfreeware.com version of date

like image 172
matchew Avatar answered Sep 19 '22 11:09

matchew