PikK45
1
Hello All,
I got a requirement when I was working with a file. Say the file has unloads of data from a table in the form
1|121|asda|434|thesi|2012|05|24|
1|343|unit|09|best|2012|11|5|
I was put into a scenario where I need the field count in all the lines in that file. It was simply achieved by
awk -F"|" '{print NF}' file
Now the case is, I need the count of characters in a field. For example,
head -2 file | awk -F"|" '{do something}'
Output should be,
1-3-4-3-5-4-2-2
1-3-4-2-4-4-2-1
Thanks
Try:
awk -F"|" '{for (i=1;i<NF;i++) printf length($i)"-";printf length($NF)"\n"}' file
1 Like
pamu
3
As per OP's input. it should be NF-1
awk -F"|" '{for (i=1;i<(NF-1);i++) printf length($i)"-";printf length($(NF-1))"\n"}' file
OR
awk -F "|" '{for(i=1;i<NF;i++){s=s?s"-"length($i):length($i)}print s;s=""}' file
Fundix
4
I guess printf length($NF)"\n" is used to make the jump line, but i do not understand its usage.
Can you detail it please ?
Thank You
It is just attaching newline character to the end of the last field's length.
1 Like
PikK45
6
Thank you guys
Especially, bartus11 & pamu. Actually I thought of using sizeof() as in C.
Alternatively:
awk '{for(i=1;i<NF;i++)$i=length($i)}NF--' FS=\| OFS=- file