[PLUG] Reformating date fields in text files
Rich Shepard
rshepard at appl-ecosys.com
Fri Jan 14 22:23:10 UTC 2022
On Fri, 14 Jan 2022, TomasK wrote:
> This is how I would do it with gensub in awk:
>
> echo "col1,01/13/2022,col3" | \
> awk -v FS=, -v OFS=, '{newDate=gensub(/\//,"-","g",$2); $2=newDate;
> print; }'
> col1,01-13-2022,col3
>
> It works by replacing all / in col2 with -
>
> If I would need to reorder/reformat the date string by split and print:
> echo "col1,01/13/2022,col3" | \
> awk -v FS=, -v OFS=, '{
> if (split($2,dateEl,"/")) {
> newDate=sprintf("%02d-%02d-%04d",dateEl[1],dateEl[2],dateEl[3]);
> $2=newDate;
> };
> print; }'
> col1,01-13-2022,col3
>
> It works by splitting the col2 into dateEl array and if successful,
> printing it reformatted as mm-dd-yyyy
Tomas,
Thank you. Those examples replace the 'sep' in the field. I also need to
re-order the field components (a[1]. a[2], a[3]) so they are replaced by
a[3], a[1], a[2] with the changed separator.
Reading about split() and gensub() in 'Effective AWK Programming' I see how
to make an array of the date field components, but not how to replace the
order in which they appear. More reading and trial-and-error is up next.
Regards,
Rich
More information about the PLUG
mailing list