Alex Rivera | Logout

What should every Perl hacker know about perl -ne?

Asked 2010-02-06T07:14:49.527
26

I have been using the Perl command line with a -ne option for years, largely to process text files in ways that sed can't. Example:

cat in.txt | perl -ne "s/abc/def/; s/fgh/hij/; print;" > out.txt

I have no idea where I learned this, and have only today read perlrun and found there are other forms (perl -pe for example).

What else should I know about perl -ne?

Edit
Report

1 Answer

28

perl -ne 'CODE' is equivalent to the program

while (<>) {
    CODE
}

perl -ane 'CODE' and perl -F/PATTERN/ -ane are also good idioms to know about. They are equivalent to

while (<>) {
    @F = split /\s+/, $_;
    CODE
}

and

while (<>) {
    @F = split /PATTERN/, $_;
    CODE
}

Example: advanced grep:

perl -ne 'print if/REGEX1/&&!/REGEX2/&&(/REGEX3/||/REGEX4/&&!/REGEX5/)' input

perl -F/,/ -ane 'print if $F[2]==4&&$F[3]ge"2009-07-01"&&$F[3]lt"2009-08-01"' file.csv


A particularly clever example that uses mismatched braces is here.

answered 2010-02-06T07:28:22.120

Your Answer