How to use a regex for the field separator in AWK? How to use a regex for the field separator in AWK? unix unix

How to use a regex for the field separator in AWK?


First of all echo doesn't auto escape and outputs a literal \n. So you'll need to add -e to enable escapes. Second of all awk doesn't support \d so you have to use [0-9] or [[:digit:]].

echo -e "1 2 foo\n2 3 bar\n42 2 baz" | awk -F '[0-9]+ [0-9]+ ' '{ print $2 }'

or

echo -e "1 2 foo\n2 3 bar\n42 2 baz" | awk -F '[[:digit:]]+ [[:digit:]]+ ' '{ print $2 }'

Both outputs:

foobarbaz 


Just replace \d with [0-9]:

With this you can print all the fields and you can see the fields immediatelly:

$ echo -e "1 2 foo\n2 3 bar\n42 2 baz" |awk -v FS="[0-9]+ [0-9]+" '{for (k=1;k<=NF;k++) print k,$k}'1 2  foo1 2  bar1 2  baz

So just use [0-9] in your command:

$ echo -e "1 2 foo\n2 3 bar\n42 2 baz" |awk -v FS="[0-9]+ [0-9]+" '{print $2}' foo bar baz