13

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?

2
  • In addition to Yeti's answer, remember that the shell splits by unquoted whitespace to create the list of arguments to awk, so instead of -F[ :] (one arg) it got -F[: and ]. This chart is quite handy (note the vertical arrows for single/double quotes).
    – arielCo
    Commented Apr 27, 2019 at 14:06
  • Thanks ArielCo, much appreciated! Commented Apr 29, 2019 at 2:18

1 Answer 1

20

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .