Haifeng Zhang
Haifeng Zhang

Reputation: 31895

How to change csv file delimiter

here's a csv file items.txt

item-number,item-description,item-category,cost,quantity-available

I tried to change the field separator from , to \n using awk and I need a easy way to do it.

1) this command does not work

awk -F, 'BEGIN{OFS="\n"} {print}' items.txt

2) this command works, but the real csv i need to process has 15+ columns, i dont want to provide all columns variables

awk -F, 'BEGIN{OFS="\n"} {print $1,$2}' items.txt

Thanks in advance.

Upvotes: 2

Views: 1075

Answers (3)

jaypal singh
jaypal singh

Reputation: 77085

You were close. After setting the OFS to newline, you will need to re-construct the fields to get them separated to newlines.

$1=$1 re-evaluates the fields and separates them by OFS which by default is space. Since we set the OFS to RS which by default is new line, you get the desired output.

The 1 at the end of statement is idiomatic way of saying print the line.

$ awk 'BEGIN{FS=",";OFS=RS}{$1=$1}1' file
item-number
item-description
item-category
cost
quantity-available

Upvotes: 1

Kevin
Kevin

Reputation: 56059

You need to get awk to re-evaluate the string by changing a field.

awk -F, 'BEGIN{OFS="\n"} {$1 = $1; print}' items.txt

Or, if you're sure the first column is always non-empty and nonzero, you could use the somewhat simpler:

awk -F, 'BEGIN{OFS="\n"} $1 = $1' items.txt

Upvotes: 1

Rubens
Rubens

Reputation: 14768

If your fields do not contain ,'s, you may use tr:

tr ',' '\n' < infile > outfile

Upvotes: 3

Related Questions