简体   繁体   中英

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.

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

-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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM