Home > Blockchain >  How can I get specific columns from a csv file that has multiple lines?
How can I get specific columns from a csv file that has multiple lines?

Time:11-29

So I need to write a script that rearranges a csv file and outputs it into another. I have a csv file that looks something like this:

name1, surname1, haircolor1
name2, surname2, haircolor2
name3, surname3, haircolor3

I need to make it so that I get the following:

haircolor1, name1
haircolor2, name2
haircolor3, name3

I've tried messing around with awk, but that jsut lists the first column, then the second etc. I'd be grateful for any input on this, thanks!

CodePudding user response:

You can try this.

awk -F, '{print $3","$1}' foo.csv
  • foo.csv is the csv file you want to process

CodePudding user response:

awk -F, -v OFS=, '{print $3,$1}'

If that causes abnormal leading whitespace, maybe try:

awk -F '[[:space:],] ' -v OFS=, '{print $3,$1}'

That splits columns on whitespace as well as commas.

  • print $3,$1 means print field 3 and 1, separated by the output field separator (OFS).
  • You can set OFS=', ' if you want to keep that leading white space.

CodePudding user response:

You can use csvcut

$ csvcut -c ' haircolor1,name1' file
 haircolor1,name1
 haircolor2,name2
 haircolor3,name3

If the alighnment is an issue, you can pipe through to sed

$ csvcut -c ' haircolor1,name1' file | sed 's/,/& /g;s/^ //'
haircolor1, name1
haircolor2, name2
haircolor3, name3

Or, using sed grouping

$ sed  's/\([^,]*\),[^,]*,\s\(.*\)/\2, \1/' file
haircolor1, name1
haircolor2, name2
haircolor3, name3
  • Related