Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl -a: How to change column separator?

I want to read the columns in a file where the separator is :.

I tried it like this (because according to http://www.asciitable.com, the octal representation of the colon is 072):

$ echo "a:b:c"  | perl -a -072 -ne 'print "$F[1]\n";' 

I want it to print b, but it doesn't work.

like image 966
Frank Avatar asked Aug 31 '11 18:08

Frank


2 Answers

Look at -F in perlrun:

% echo "a:b:c" | perl -a -F: -ne 'print "$F[1]\n";'
b

Note that the value is taken as regular expression, so some delimiters may need some extra escaping:

% echo "a.b.c" | perl -a -F. -ne 'print "$F[1]\n";'

% echo "a.b.c" | perl -a -F\\. -ne 'print "$F[1]\n";'
b
like image 125
toolic Avatar answered Oct 22 '22 21:10

toolic


-0 specifies the record (line) separator. It was cause Perl to receive three lines:

>echo a:b:c | perl -072 -nE"say"
a:
b:
c

Since there's no whitespace on any of those lines, $F[1] would be empty if -a were to be used.

-F specifies the input field separator. This is what you want.

perl -F: -lanE'say $F[1];'

Or if you're stuck with an older Perl:

perl -F: -lane'print $F[1];'

Command line options are documented in perlrun.

like image 25
ikegami Avatar answered Oct 22 '22 23:10

ikegami