Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is your latest useful Perl one-liner (or a pipe involving Perl)? [closed]

The one-liner should:

  • solve a real-world problem
  • not be extensively cryptic (should be easy to understand and reproduce)
  • be worth the time it takes to write it (should not be too clever)

I'm looking for practical tips and tricks (complementary examples for perldoc perlrun).

like image 243
jfs Avatar asked Sep 21 '08 19:09

jfs


People also ask

What is pipe in Perl?

Perl's open function opens a pipe instead of a file when you append or prepend a pipe symbol to the second argument to open . This turns the rest of the arguments into a command, which will be interpreted as a process (or set of processes) that you want to pipe a stream of data either into or out of.

What is Perl NLE?

Strip out lines Use perl -nle 'print if ! … ' to say “print, except for the following cases.” Practical uses include omitting lines matching a regular expression, or removing the first line from a file.


3 Answers

Please see my slides for "A Field Guide To The Perl Command Line Options."

like image 86
Andy Lester Avatar answered Nov 10 '22 04:11

Andy Lester


Squid log files. They're great, aren't they? Except by default they have seconds-from-the-epoch as the time field. Here's a one-liner that reads from a squid log file and converts the time into a human readable date:

perl -pe's/([\d.]+)/localtime $1/e;' access.log

With a small tweak, you can make it only display lines with a keyword you're interested in. The following watches for stackoverflow.com accesses and prints only those lines, with a human readable date. To make it more useful, I'm giving it the output of tail -f, so I can see accesses in real time:

tail -f access.log | perl -ne's/([\d.]+)/localtime $1/e,print if /stackoverflow\.com/'
like image 40
pjf Avatar answered Nov 10 '22 05:11

pjf


The problem: A media player does not automatically load subtitles due to their names differ from corresponding video files.

Solution: Rename all *.srt (files with subtitles) to match the *.avi (files with video).

perl -e'while(<*.avi>) { s/avi$/srt/; rename <*.srt>, $_ }'

CAVEAT: Sorting order of original video and subtitle filenames should be the same.

Here, a more verbose version of the above one-liner:

my @avi = glob('*.avi');
my @srt = glob('*.srt');

for my $i (0..$#avi)
{
  my $video_filename = $avi[$i];
  $video_filename =~ s/avi$/srt/;   # 'movie1.avi' -> 'movie1.srt'

  my $subtitle_filename = $srt[$i]; # 'film1.srt'
  rename($subtitle_filename, $video_filename); # 'film1.srt' -> 'movie1.srt'
}
like image 23
jfs Avatar answered Nov 10 '22 05:11

jfs