Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing column separated by comma using Awk command line

Tags:

csv

awk

I have a problem here. I have to print a column in a text file using awk. However, the columns are not separated by spaces at all, only using a single comma. Looks something like this:

column1,column2,column3,column4,column5,column6 

How would I print out 3rd column using awk?

like image 567
user3364728 Avatar asked Nov 10 '14 11:11

user3364728


People also ask

How do you put commas in awk?

The unquoted commas in the print part tell AWK to use the chosen field separator (in this case, a comma) when printing. Note the extra commas in quotes – that's how the blank columns are added. First a comma is printed, then $1, then a comma, then $2...

What is awk '{ print $3 }'?

txt. If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

How do you use a field separator in awk?

Just put your desired field separator with the -F option in the AWK command and the column number you want to print segregated as per your mentioned field separator. Show activity on this post. AWK works as a text interpreter that goes linewise for the whole document and that goes fieldwise for each line.


2 Answers

Try:

awk -F',' '{print $3}' myfile.txt 

Here in -F you are saying to awk that use , as the field separator.

like image 183
SMA Avatar answered Sep 17 '22 09:09

SMA


If your only requirement is to print the third field of every line, with each field delimited by a comma, you can use cut:

cut -d, -f3 file 
  • -d, sets the delimiter to a comma
  • -f3 specifies that only the third field is to be printed
like image 25
Tom Fenech Avatar answered Sep 21 '22 09:09

Tom Fenech