Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested awk command

Tags:

bash

shell

awk

I have a file with this syntax:

foo:bar:value1,value2,value3,...:foo:bar

I want to get the value list (space separated) which does not have a fixed length:

value1 value2 value3 ...

Is there a way to do this in a single awk command ? Instead of piping commands like that:

awk -F: '{print $3}' myfile.txt | awk -F, '{OFS=" "; $1 = $1; print $0}'
like image 638
jmlemetayer Avatar asked Oct 21 '25 16:10

jmlemetayer


2 Answers

You can use Awk's split() function to do additional splitting.

awk -F : '{ split($3, a, ","); print a[1], a[2], a[3] }' file
like image 81
tripleee Avatar answered Oct 23 '25 08:10

tripleee


If you know which field to grab the csv separated values, then you can use gsub function too:

awk -F: '{gsub(/,/," ",$3);print $3}' file

$ cat file
foo:bar:value1,value2,value3,value3:foo:bar
foo:bar:value1,value2:foo:bar
foo:bar:value1,value2,value3,value4,value5,value6:foo:bar

$ awk -F: '{gsub(/,/," ",$3);print $3}' file
value1 value2 value3 value3
value1 value2
value1 value2 value3 value4 value5 value6
like image 39
jaypal singh Avatar answered Oct 23 '25 08:10

jaypal singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!