one-liners intermediate

How to process CSV files with Perl one-liners

Question

How can I quickly extract columns from CSV files using Perl?

Use the -F flag to specify a custom field separator and @F to access fields:

# Extract first column from CSV
perl -F',' -ane 'print $F[0], "\n"' data.csv

# Extract multiple columns (1st and 3rd)
perl -F',' -ane 'print "$F[0],$F[2]\n"' data.csv

# Filter rows where 2nd column > 100
perl -F',' -ane 'print if $F[1] > 100' data.csv

# Sum values in 3rd column
perl -F',' -ane '$sum += $F[2]; END { print "$sum\n" }' data.csv

# Skip header and process
perl -F',' -ane 'print if $. > 1' data.csv

# Example CSV:
# name,age,score
# Alice,25,95
# Bob,30,87

# Note: For complex CSV (quoted fields), use Text::CSV module

The $. variable contains the current line number. For production CSV parsing, use the Text::CSV module.

Was this helpful?

Related Questions