1

I have a file that contains the below records:

**cat Date.txt** SEPT,30-SEP-2017 MARCH,30-MAR-2018 JULY,30-JUL-2017 DECEM,30-DEC-2017 AUGS,30-AUG-2017 

I want the output to be:

 SEPT,20170930 MARCH,20180330 JULY,20170730 DECEM,20171230 AUGS,20170830 

I have done a script with a while loop, as given below.

 cat Date.txt > /tmp/exp.part while read line do Dat=$(echo $line | awk -F , '{print $1}') DatNew=$(date -d $Exp +%Y%m%d) echo $DatNew done < /tmp/exp.part 

I want to know if I can do it from the awk command, instead of writing a while loop.

2 Answers 2

2

One way using system command within awk: Input file:

$ cat file 27-SEP-2017 28-MAR-2018 27-JUL-2017 27-DEC-2017 29-AUG-2017 $ awk '{system("date -d " $0 " +%Y%m%d")}' file 20170927 20180328 20170727 20171227 20170829 

For the updated input file:

$ cat file SEP,27-SEP-2017 MAR,28-MAR-2018 JUL,27-JUL-2017 DEC,27-DEC-2017 AUG,29-AUG-2017 $ awk -F, '{system("date -d " $2 " +%Y%m%d")}' file 20170927 20180328 20170727 20171227 20170829 

For the updated requirement:

$ cat file SEPT,30-SEP-2017 MARCH,30-MAR-2018 JULY,30-JUL-2017 DECEM,30-DEC-2017 AUGS,30-AUG-2017 $ awk -F, '{cmd="date -d "q $2 q" "s"+%Y%m%d"s; cmd|getline x;print $1,x}' dq='"' sq="'" OFS=, file SEPT,20170930 MARCH,20180330 JULY,20170730 DECEM,20171230 AUGS,20170830 
Sign up to request clarification or add additional context in comments.

7 Comments

Can you print your exact input file contents?
$ cat file SEP,27-SEP-2017 MAR,28-MAR-2018 JUL,27-JUL-2017 DEC,27-DEC-2017 AUG,29-AUG-2017 $ awk '{system("date -d " $0 " +%Y%m%d")}' file date: invalid date SEP,27-SEP-2017' date: invalid date MAR,28-MAR-2018' date: invalid date JUL,27-JUL-2017' date: invalid date DEC,27-DEC-2017' date: invalid date `AUG,29-AUG-2017'
Can you format your content better? I am not able to make out whether the whole content is in the same line or different lines?
Updated the solution
Perfect, but I want the first column as well. Which will be like: SEP,20170927
|
0

Following on Guru's answer, this also seemed to work:

$ awk -F, '{cmd="date -d "$2" +%Y%m%d"; cmd|getline x;print $1,x}' OFS=',' file SEPT,20170930 MARCH,20180330 JULY,20170730 DECEM,20171230 AUGS,20170830 

Note the awk version was actually mawk:

$ awk -W version mawk 1.3.3 Nov 1996, Copyright (C) Michael D. Brennan 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.