Is there a way to make awk detect content separated by commas (or any other character) instead of spaces?

e.g. a file (.csv) contains a list of contacts in the format "title","first-name","last-name","e-mail". How would you use awk to print all the first names?

  • awk -F, '{print $2}' -F specifies field separator and 2nd field is where first name is stored – MelBurslan Feb 17 '16 at 14:54
  • @MelBurslan Thank you. A small additional question: the tutorial I'm working through puts the single quote marks inside the brackets: awk {'print $2'}. Is one (i.e. inside or outside) better than the other / preferred? – penname Feb 17 '16 at 15:09
  • makes no difference which one comes first. It is a programming style. From my personal experience, awk -F, '{ awk commands here }' is the preferred usage, but at the end it doesn't matter if ' or { comes first. It even works with wrong order of signs, such as awk -F, '{print $2'} filename.. notice the open and close sequence of signs. But it is a very sloppy programming exercise and should not be encouraged, in my opinion – MelBurslan Feb 17 '16 at 15:21
  • @MelBurslan Thank you - that's very helpful. – penname Feb 17 '16 at 16:17

You need to set the field separator, either as a command line option

awk -F, '{print $2}' file.csv

or using the built-in FS variable

awk 'BEGIN{FS=","} {print $2}' file.csv

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