How to reorder fields using AWK?

I have a file with the following location:

123,01-08-2006 124,01-09-2007 125,01-10-2009 126,01-12-2010 

How can I convert it to the next using AWK?

 123,2006-08-01 124,2007-09-01 125,2009-10-01 126,2009-12-01 
+4
source share
4 answers

Did not read the question correctly for the first time. You need a field separator, which can be a dash or a comma. After that, you can use the dash as a separator for the output fields (as is most common) and fake the comma using concatenation:

 awk -F',|-' 'OFS="-" {print $1 "," $4,$3,$2}' file 
+3
source

Pure awk

 awk -F"," '{ n=split($2,b,"-");$2=b[3]"-"b[2]"-"b[1];$i=$1","$2 } 1' file 

Sed

 sed -r 's/(^.[^,]*,)([0-9]{2})-([0-9]{2})-([0-9]{4})/\1\4-\3-\2/' file sed 's/\(^.[^,]*,\)\([0-9][0-9]\)-\([0-9][0-9]\)-\([0-9]\+\)/\1\4-\3-\2/' file 

Bash

 #!/bin/bash while IFS="," read -rab do IFS="-" set -- $b echo "$a,$3-$2-$1" done <"file" 
+2
source

Unfortunately, I believe that the standard awk only allows one field delimiter, so you have to pre-process the data. You can do this with tr , but if you really need an awk -only solution, use:

 pax> echo '123,01-08-2006 124,01-09-2007 125,01-10-2009 126,01-12-2010' | awk -F, '{print $1"-"$2}' | awk -F- '{print $1","$4"-"$3"-"$2}' 

It is output:

 123,2006-08-01 124,2007-09-01 125,2009-10-01 126,2010-12-01 

optional.

The first awk changes the characters , to - , so you have four fields separated by the same character (this is the bit that I usually used tr ',' '-' for).

The second awk prints them in the order you specify, while adjusting the field separators.

If you are using an awk implementation that allows multiple FS characters, you can use something like:

 gawk -F ',|-' '{print $1","$4"-"$3"-"$2}' 
+1
source

If this is not necessarily awk, you can also use Perl:

 $ perl -nle 'print "$1,$4-$3-$2" while (/(\d{3}),(\d{2})-(\d{2})-(\d{4})\s*/g)' < file.txt 
0
source

All Articles