Saturday, June 27, 2020

How to Column Grep a CSV File (Perl)

You know what I mean.. only show rows where entries in a particular column match a certain criterion.

You only want to see the rows, where field number 10 (index 11 for hackers :) matches your regex. How?

Good news is, phew, perl trumps awk hands down AFAIK.

$ > perl -F, -ane 'print if $F[ordinal_field_num_minus_1] =~ /regex/;' filename

Does it.
So, if you're interested in the first column (i.e., ordinal number is 1, then use $F[0]. YGTI :)

Wha?

-a is the autosplit option - it auto splits each line read in into the @F array, but it uses ' ' (space) as the character to split on. You change that using -F (same as awk). Note that you can do -F'regex' if you want, for -F'[:,]'

If you need to get up to speed on -a, -n, -e, -F and the very useful -l, read $ > man perlrun

No comments: