awk substr delimeter

Hi All,

I have an awk command that uses the substr function - At the moment I know the length of the values so can use the example below i.e substr(i,0,1)

However in future these lengths may change so wondered if you can use a delimiter within a substr? Like in bash you could use cut -d ';', is there a similar function in awk?

awk 'BEGIN{FS=OFS=","}
NR==1{print;next}
{a[$4";"$7";"$8";"$13]+=$9}
END{for(i in a)print $1, $2, $3, substr(i,0,1), $5, $6, substr(i,3,10), substr(i,14,10), a, $10, $11, $12}' file.txt

IN the above example

 
 i=2;2015-12-01;2016-12-01;Y1
 

If for example the first value (2) changed to 0002 then substr(i,0,1) would not pick up the entire value.

Thanks in advance for your help.

Why don't you use the split function?

Hi Rudi,

I am not aware of the Split function - Can you provide an example please?

man awk :

---------- Post updated at 15:07 ---------- Previous update was at 15:07 ----------

awk 'BEGIN {n = split ("i=2;2015-12-01;2016-12-01;Y1", T, ";"); for (i=1; i<=n; i++) print "T[" i "]: ", T}'
T[1]:  i=2
T[2]:  2015-12-01
T[3]:  2016-12-01
T[4]:  Y1

Rudi,

I have the below code;

awk 'BEGIN{FS=OFS=","}
NR==1{print;next}
{a[$4";"$7";"$8";"$13]+=$9}
END{for(i in a) print $1, $2, $3, split(i,b,";") b[1]}' BUCKETED.csv > COL_TOTAL.csv

However when I run, the output is as below

C,ABC,ABCD,43
C,ABC,ABCD,43
C,ABC,ABCD,43
C,ABC,ABCD,43
C,ABC,ABCD,43
C,ABC,ABCD,44

The code seems to be adding 4 at the beginning of all the values.

I tried moving split to the start

awk 'BEGIN{FS=OFS=","}
NR==1{print;next}
{a[$4";"$7";"$8";"$13]+=$9}
END{for(i in a) split(i,b,";"); print $1, $2, $3, b[1]}' BUCKETED.csv > COL_TOTAL.csv

But this only output one record and with the wrong value again

C,ABC,ABCD,4

The 4 is the element count from the conversion; see above:

Can't you see the error in

?

---------- Post updated at 16:54 ---------- Previous update was at 16:52 ----------

Enclose split and print in curly braces:

{for(i in a) {split(i,b,";"); print $1, $2, $3, b[1]}}

Apologies - new to awk and trying to get my head around the syntax. This solution works great, thanks again for your help.