0

Given an input like this:

field1,field2,field3,field4

I would like to get an output like this

field1
field2
field3
field4

How can I do this with awk?

  • 2
    how "like that" is your actual data? Because if there are multiple lines of input, you'll have more trouble distinguishing records afterwards (if that's even a problem). – Jeff Schaller Mar 18 at 13:41
  • Does any field contain embedded commas? – Kusalananda Mar 18 at 13:45
  • No embedded commas. Source file will have multiple lines but i mean to obtain just one before applying this parse – Santi Mar 18 at 14:31
3

The idiomatic Awk way of doing this would probably be

awk 'BEGIN{FS=","; OFS="\n"} {$1=$1} 1'

or equivalently

awk '{$1=$1} 1' FS=, OFS='\n'

The {$1=$1} just forces re-evaluation of the record with the new separator OFS, and the 1 triggers the default print action. You can use other expressions, such as NF += 0, to force the re-evaluation if you prefer - it's a matter of preference.

A quick'n'dirty way would be

awk -vRS=, 1

(or awk 1 RS=,) which treats each comma-separated word as a whole record and outputs them with the default newline record separator.

3

Using bash and csvformat from the csvkit collection to change the field delimiter from a comma to a newline:

$ csvformat -D $'\n' file
field1
field2
field3
field4

This is assuming that the input in file is properly formatted CSV. This would also properly handle embedded commas:

$ cat file
"field,1",field2,field3,field4
$ csvformat -D $'\n' file
field,1
field2
field3
field4
2

Use tr to translate the comma to a newline:

echo "field1,field2,field3,field4" | tr "," "\n"

This is likely faster than using awk, though if you insist, you could do:

echo "field1,field2,field3,field4" | awk '{gsub(",","\n");print}'

From the GNU awk documentation:

gsub(regexp, replacement [, target])

Search target for all of the longest, leftmost, nonoverlapping matching substrings it can find and replace them with replacement. The ‘g’ in gsub() stands for “global,” which means replace everywhere.

  • Thanks, the tr solution is just what i needed – Santi Mar 18 at 14:35

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.