0

I have sample.txt file in my linux system.all the data that is present in my file are in the following date format

            Mon Apr 24 16:14:06 PDT 2017
            Tue Apr 25 13:31:25 PDT 2017
            Mon Apr 03 13:53:03 PDT 2017
            Sun Feb 05 16:19:27 PST 2017
            Sun Feb 05 17:51:42 PST 2017
            Sun Feb 05 18:16:21 PST 2017
            Sun Feb 05 19:17:33 PST 2017
            Sun Feb 05 21:14:23 PST 2017
            Sat Feb 04 10:39:33 PST 2017
            Sat Feb 04 10:46:52 PST 2017
            Sat Feb 04 14:35:27 PST 2017

I want to convert all this date format in my sample.txt file to YYYY-MM-DD Format.

sande
  • 567
  • 1
  • 10
  • 24

2 Answers2

1

It's quite simple with date -d, e.g.

while read -r line; do 
    echo $(date -d "$line" +%Y-%m-%d); 
done < file.txt

Input File

$ cat file.txt
            Mon Apr 24 16:14:06 PDT 2017
            Tue Apr 25 13:31:25 PDT 2017
            Mon Apr 03 13:53:03 PDT 2017
            Sun Feb 05 16:19:27 PST 2017
            Sun Feb 05 17:51:42 PST 2017
            Sun Feb 05 18:16:21 PST 2017
            Sun Feb 05 19:17:33 PST 2017
            Sun Feb 05 21:14:23 PST 2017
            Sat Feb 04 10:39:33 PST 2017
            Sat Feb 04 10:46:52 PST 2017
            Sat Feb 04 14:35:27 PST 2017

Example Use/Output

$ while read -r line; do echo $(date -d "$line" +%Y-%m-%d); done < file.txt
2017-04-24
2017-04-25
2017-04-03
2017-02-05
2017-02-05
2017-02-05
2017-02-05
2017-02-05
2017-02-04
2017-02-04
2017-02-04
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

I don't know if it's the best way to do this but this should work

awk '{print $6"-"$2"-"$3}' file.txt | sed 's/Jan/01/g; s/Feb/02/g; s/Mar/03/; s/Apr/04/g; s/May/05/g; s/Jun/06/g; s/Jul/07/g; s/Aug/08/g; s/Sep/09/g; s/Oct/10/g; s/Nov/11/g; s/Dec/12/g'
nando
  • 501
  • 5
  • 6