Reputation: 439
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.
Upvotes: 1
Views: 2253
Reputation: 48
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
Upvotes: 0
Reputation: 17054
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
Upvotes: 2