Blog Archive

Tuesday, January 15, 2013

Perl lane command study note






ps auxwww | head -n3 | perl -lape '$_ = join(" ", @F[ 1,10..$#F ])'

The $#F in the above command is a Perl shortcut meaning "the index of the last element of the @F array". The full expression inside the brackets of @F[ ... ] specifies an array slice: multiple elements of the array, forming an array in themselves. Thus, the larger @F expression means "the array consisting of the second element of @F as well as all fields from the 11th to the last".


# The following display how can you pass a variable from unix environment into perl environment, which works like a bridge. (Note: $EVN{re})
n="'" && sed -e '1,13d' scan_model_libsvm0114 | env re="$n"   perl -lane ' print "grep  $ENV{re}@F[5..$#F]$ENV{re} a.tmp"' | head -n1

Perl maintains environment variables in a special hash named %ENV .

perl -F: -lane 'print $F[0]' /etc/passwd

Trick #7: \K
\K is undoubtedly my favorite little-known-feature of Perl regular expressions. If \K appears in a regex, it causes the regex matcher to drop everything before that point from the internal record of "Which string did this regex match?". This is most useful in conjunction with s///, where it gives you a simple way to match a long expression, but only replace a suffix of it.
Suppose I want to replace the From: field in an email. We could write something like
perl -lape 's/(^From:).*/$1 Nelson Elhage <nelhage\@ksplice.com>/'
But having to parenthesize the right bit and include the $1 is annoying and error-prone. We can simplify the regex by using \K to tell perl we won't want to replace the start of the match:
perl -lape 's/^From:\K.*/ Nelson Elhage <nelhage\@ksplice.com>/'

Trick #9: BEGIN and END
BEGIN { ... } and END { ... } let you put code that gets run entirely before or after the loop over the lines.
For example, I could sum the values in the second column of a CSV file using:
perl -F, -lane '$t += $F[1]; END { print $t }'

No comments:

Post a Comment