Junba Tester
Junba Tester

Reputation: 851

How to get the first column of every line from a CSV file?

How do get the first column of every line in an input CSV file and output to a new file? I am thinking using awk but not sure how.

Upvotes: 50

Views: 88244

Answers (6)

Chris Koknat
Chris Koknat

Reputation: 3451

Using Perl:

perl -F, -lane 'print $F[0]' data.txt > data2.txt

These command-line options are used:

  • -n loop around every line of the input file
  • -l removes newlines before processing, and adds them back in afterwards
  • -a autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace.
  • -e execute the perl code
  • -F autosplit modifier, in this case splits on ,

If you want to modify your original file in-place, use the -i option:

perl -i -lane 'print $F[0]' data.txt


If you want to modify your original file in-place and make a backup copy:

perl -i.bak -lane 'print $F[0]' data.txt


If your data is whitespace separated rather than comma-separated:

perl -lane 'print $F[0]' data.txt

Upvotes: -1

kenorb
kenorb

Reputation: 166429

This can be achieved using grep:

$ grep -o '^[^,]\+' file.csv

Upvotes: 1

Debaditya
Debaditya

Reputation: 2497

Input

a,12,34
b,23,56

Code

awk -F "," '{print $1}' Input

Format

awk -F <delimiter> '{print $<column_number>}' Input

Upvotes: 5

Levon
Levon

Reputation: 143022

Try this:

 awk -F"," '{print $1}' data.txt

It will split each input line in the file data.txt into different fields based on , character (as specified with the -F) and print the first field (column) to stdout.

Upvotes: 91

Nykakin
Nykakin

Reputation: 8747

echo "a,b,c" | cut -d',' -f1 > newFile

Upvotes: 12

user647772
user647772

Reputation:

Can be done:

$ cut -d, -f1 data.txt

Upvotes: 72

Related Questions