[PLUG] Reformating date fields in text files

TomasK tomas.kuchta.lists at gmail.com
Fri Jan 14 22:36:00 UTC 2022


On Fri, 2022-01-14 at 14:23 -0800, Rich Shepard wrote:
> 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.
> 

Is that a thin veiled request that I change the dateEl array index
order in the sprint command? I hope not.

Please try to comprehend this trivial example - it will help you
solving you next problem. It is written as single line copy past
example to your shell.

I do not want to sound patronizing - if this is not something you can
figure out - please seriously consider signing up for 2 semesters of
basic computer science/programming classes. I get Portland community
catalog every year - they do have some on offer. It is great for
understanding basic programming concepts and having some practice aimed
at comprehension.

Tomas 



More information about the PLUG mailing list