9

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?

  • 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 Apr 27 at 14:06
  • Thanks ArielCo, much appreciated! – Swapnil Dhule Apr 29 at 2:18
13

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.