Two field separators (colon and space) in awk

awk

How can we specify two field separators in awk command when one of them is space? I think this can be done by using an embedded if-else condition in awk, however I am not sure about the exact command.

Sample file is as below:

cat test.txt
Swapnil Engineer 20000
Avinash:Doctor:30000
Dattu GovntJob 50000
Amol:Master:10000

I want to print the second column ($2). Expected output is:

Engineer
Doctor
GovntJob
Master

When I tried to put both space and colon as field seperators, it failed with a syntax error:

awk -F[ :] '{print $2}' test.txt
awk: cmd. line:1: :]
awk: cmd. line:1: ^ syntax error

How can we use two field separators and utilize awk functionality?

Best Answer

You are on the right track!
Just add the missing quotes around [ :]:

awk -F'[ :]' '{print $2}' test.txt
Engineer
Doctor
GovntJob
Master
Related Question