Getting Started
Introduction
Perl IDEs
History
Advice
Tools
Mini-Tutorial
Tutorial
Code Snippets

Resources
Top Sites
More Tutorials
Books
Magazines
Articles
NewsLetters
Mailing Lists
NewsGroups
Forums
User Groups
Talk Shows
Blogs
Clothing

GBIC >> Perl >> Information Center Tutorials >> One Liners >> Scripts

Perl Information Center Tutorials - One Liner Summary
These tutorials were written to help you get a quick, but thorough, understanding of Perl - the
scope of the language as well as it's specific capabilities.

Beginners Built-In Functions     Advanced CGI Applications

One Liners
Perl allows a complete, single line script to be run from the command line. These 'one liners'
can be a quick way of making changes, finding information or presenting file content.

Most Perl programmers don't use one liners and are happy to use more relaxed, readable
code in standard multi-line script files. Other programmers enjoy the speed and convenience
of one liners or simply enjoy the challenge of cramming as much code/logic into one line as
possible.

The following three sections provide information on how to create one liners, over 75 scripts,
and detailed explanation of how the scripts work.

One Liner Categories
What can you do with one liners? The following list is a categorical listing of the one liners provided
in this tutorial. The corresponding scripts are provided below.

    Find and Replace
  • Pattern
  • Pattern (redirect)
  • Pattern (edit in place)
  • Left/Right spaces
  • Left spaces
  • Right spaces
  • Collapse spaces
  • Remove first column
  • Replace blank lines
  • Remove blank lines
  • Collapse blank lines
    Insert
  • Double space
  • Line at top
  • Line at bottom
  • Line at arbitrary position
  • Line numbers
  • Columns
    Print
  • First matching line
  • Matching lines
  • Matching content
  • Matching lines/filename
  • Non-matching lines
  • Non-blank lines
  • Non-comments lines
  • Lines before marker
  • Lines through marker
  • Lines between markers
  • Lines outside markers
  • Line 1
  • Line r
  • Lines r..s
  • Lines outside r..s
  • Lines between r..s
  • First n lines
  • Last n lines
  • Last line
  • Long lines
  • Specific column
  • Matching paragraphs
  • All words
  • Unique words
  • Duplicate words
    Format
  • Lower case text
  • Lower case text (UC 1st)
  • Upper case 1st char
  • Lower case filenames
  • Upper case filenames
  • Wordwrap
    Reverse
  • Characters in Line
  • Characters in File
  • Lines
  • Columns
  • Paragraphs
    HTML
  • Add Title info
  • Add Footnote
  • Extract URLs
    Statistics
  • Character count
  • Vowel count
  • Character distribution
  • Word distribution
  • Line count
  • Word count
  • Unique word count
  • Duplicate word count
    Math
  • Add command line numbers
  • Add columns (r plus s)
  • Add columns (r thru s)
  • Add lines (column 1)
  • Add lines (column n)
  • Increment all numbers
  • Create random numbers
  • Rot13 Encryption
  • Test number for prime

Single Line Summary of One Liners
And here are the one liner scripts. Several of the categories list multiple ways to perform
the task. Alternatives are presented in random order.

    Test Before Using

    Syntax:                   perl -wc script.pl
    CGI module version:       perl -MCGI -e "print $CGI::VERSION"
    Contents of @INC:         perl -e "foreach $a (@INC) { print qq/$a\n/}"
    

    Find and Replace

    Pattern:                  perl -pe "s/aaa/bbb/g" input.txt
                              perl -pe "s/\baaa\b/bbb/g" input.txt
    Pattern (redirect):       perl -pe "s/aaa/bbb/g" input.txt > output.txt
                              perl -pe "s/\naaa/\bbbb/g" input.txt > output.txt
    Pattern (edit in place):  perl -i.bak -pe "s/aaa/bbb/g" input.txt
                              perl -i.bak -pe "s/\baaa/\bbbb/g" input.txt
    Left/Right spaces:        perl -lpe "s/^\s+//;s/\s+$//" input.txt
    Left spaces:              perl -lpe "s/^\s+//" input.txt
    Right spaces:             perl -lpe "s/\s+$//" input.txt
    Collapse spaces:          perl -pe "s/( )+\1/$1/g" input.txt
    Remove first column:      perl -nale 'shift@F;print"@F"'
    Replace blank lines:      perl -ne "/\S/? print : print qq/subtext\n/" input.txt
                              perl -ne "/\S/ && print" input.txt
    Remove blank lines:       perl -pe "unless (/\S/) {$_=''}" input.txt
                              perl -ane "@F && print" input.txt
                              perl -lp00ee input.txt
    Collapse blank lines:     perl -0777 -pe "s/\n+/\n\n/g;chop" input.txt
                              perl -00 -pi.bak -e 1 input.txt
    

    Insert

    Double space:             perl -pe "$_.=$/" input.txt
                              perl -pe "$_.=qq/\n/" input.txt
                              perl -0777 -lpe "s/\n/\n\n/g" input.txt
    Line at top:              perl -e "@a=<>;print qq/new line\n/;print @a" input.txt > output.txt
                              perl -0777 -pe "print qq/newline\n/" input.txt
                              perl -pe "print qq/newline\n/ if $.==1" input.txt
                              perl -e "@a = <>; unshift (@a,qq/newline\n/);print @a" input.txt
    Line at bottom:           perl -e "@a=<>;print @a; print qq/new line\n/" input.txt > output.txt
                              perl -0777 -pe " END {print qq/\nnewline/}" input.txt
                              perl -e "open (IN,'>>input.txt');print IN qq/\nnewline/"
    Line at arbitrary pos:    perl -pi.bak -le "print 'New line added!!' if $. == 3" input.txt
                              perl -pi.bak -le "print 'New line added!!' if $. == 3; close ARGV if eof" input1.txt input2.txt
    Line numbers:             perl -pe "$_ = sprintf '%04d %s', $., $_" input.txt
                              perl -pe "$_ = qq/$.\t$_/" input.txt
                              perl -pe "$_ = qq/$. - $_/" input.txt
    Columns:                  --
    

    Conversion

    DOS to Unix:              perl -i.bak -pe "s/\n/\r/g" input.txt
    Unix to DOS:              perl -i.bak -pe "s/\r/\n/g" input.txt
    

    Print

    First Matching line:      perl -ne "print and last if /pattern/" input.txt
    Matching lines:           perl -nle "print if /pattern/" input.txt
    Matching content:         perl -nle "print $1 if /(pattern)/" input.txt
    Matching lines/filename:  perl -nle "print qq/$ARGV: $_/ if /pattern/" input1.txt input2.txt
    Non-matching lines:       perl -nle "print unless /(pattern)/" input.txt
    Non-blank lines:          perl -ne "print if /\S/" input.txt
                              perl -ne "print unless /^$/" input.txt
    Non-comment lines:        perl -ne "print unless /^#/" input.txt
    Lines before marker:      perl -pe "last if /^START$/" input.tx
    Lines through marker:     perl -ne "print; last if /pattern/" input.txt
    Lines between markers:    perl -ne "print if /^START$/ .. /^END$/" input.txt
    Lines outside markers:    perl -ne "print if ! /^START$/ .. /^END$/"
    Line 1                    perl -e "$_=<>;chomp;print" input.txt
    Line r                    perl -nle "print if $. == 5" input.txt
                              perl -ne 'print and exit if $. == 5' file
                              perl -ne 'print and last if $. == 5' file
    Lines r .. s:             perl -ne "print if 5 .. 8" input.txt
                              perl -ne "print if $. >= 5; exit if $. >= 8" input.txt
    Lines outside r..s:       perl -ne "print unless 5 .. 8" input.txt
                              perl -ne "print if $. < 5 || $. > 8;" input.txt
    Lines between r..s:       perl -ne "print if 5+1 .. 8-1" input.txt
                              perl -ne "print if $. > 5 && $. < 8; exit if $. >= 8" input.txt
    First n lines:            perl -pe "exit if $. > 5" input.txt
                              perl -ne "print if 1 .. 5" input.txt
    Last n lines:             perl -e "@a = <>; print @a[$#a-5+1 .. $#a]" input.txt
    Last line:                perl -e "@a = <>; print $a[$#a]" input.txt
                              perl -e "print+()[-1]" input.txt
    Long lines:               perl -ne "print if length > 80" input.txt
    Specific column:          perl -pale "$_=$F[1]" input.txt
                              perl -ple "@a=split;$_=$a[1]" input.txt
    Matching paragraphs:      perl -00 -ne "print if /pattern/" input.txt
    All words:                perl -0777 -lne "foreach (sort split){print qq/$_\n/}" input.txt
    Unique words:             perl -0777 -ne "foreach (sort split){print qq/$_\n/ if $_ ne $old; $old=$_}" input.txt
                              perl -0777 -ane "@U{@F}=();print join(qq/\n/,sort keys %U)" input.txt
    Duplicate words:          perl -0777 -ne "foreach (sort split){print qq/$_\n/ if $_ ne $old; $old=$_}" input.txt
    Double quoted strings:    perl -lne "print $1 while (/\"(.*?)\"/g)" input.txt
    
    

    Format

    Lower case text:          perl -pe "$_=lc $_" input.txt  
                              perl -ne "print lc" input.txt  
                              perl -pe "tr/A-Z/a-z/" input.txt
    Lower case text (UC 1st): perl -ne "print ucfirst lc" input.txt
                              perl -pe "s/(\w)(.*)$/\U$1\L$2/" input.txt 
                              perl -pe "s/\w.+/\u\L$&/" input.txt        
    Upper case 1st char:      perl -ne "print ucfirst $_" input.txt  
                              perl -pe "s/(\w)(.*)$/\u$1$2/" input.txt 
                              perl -pe "s/\w.+/\u$&/" input.txt        
    Lower case filenames:     perl -e "@f=<*.jpg>;foreach (@f) {rename $_, lc($_) }"
                              perl -e "for (glob qq/*jpg/) { rename $_, lc($_) }"
    Upper case filename:      perl -e "@f=<*.jpg>;foreach (@f) {rename $_, uc($_) }"
                              perl -e "for (glob qq/*jpg/) { rename $_, uc($_) }"
    Wordwrap:                 perl -000 -pe "tr/ \t\n\r/ /;s/(.{50,72})\s/$1\n/g;$_.=qq/\n/x2" input.txt
    

    Reverse

    Characters in each line:  perl -nle "print scalar reverse $_" input.txt
    Characters in file:       
    Lines in each file:       perl -e "@L=reverse<>; chomp @L; print join(qq/\n/,@L)" input.txt
    Columns in each file:     perl -lane "@new = reverse @F; print join(' ',@new)" input.txt
    Paragraphs in each file:  perl -00 -e "print reverse <>" input.txt
    

    HTML

    Get URL                   perl -e "use LWP::Simple; getprint 'http://www.garybeene.com'"
                              perl -MLWP::Simple -e "getprint 'http://www.garybeene.com'"
    Add Title info:           perl -pe "s/<title>/<title>garybeene.com/i" input.txt
    Add Footnote:             perl -pe "s/<\/body>/<address>Gary Beene<\/address><\/body>/i" input.txt
    Extract URLs:             perl -nle "print $1 while /\<a\b[^\>\"]*?\bhref\s*=\s*[\"]?([^\>\"]*)/gi" input.txt
    

    Statistics

    Character count:          perl -lne "$c += length; END { print $c }" input.txt
                              perl -0777 -ne "s/\n//g; print length($_)" input.txt
    Vowel count:              perl -ne "END{print $c} $c += tr/aeiou//" input.txt
    Character distribution:   perl -0777 -ne "s/\n//g;@C=split//;for(@C){$C{$_}++} END{for(sort keys %C){print qq/$_,: $C{$_}\n/}}" input.txt
    Word distribution:        perl -ane "for(@F){$F{$_}++} END{for(sort keys %F){print qq/$_: $F{$_}\n/}}" input.txt
    Line count:               perl -ne "END { print $. }" input.txt
                              perl -e "@L=<>; print scalar @L" input.txt
                              perl -ne "END {print $.}" input.txt
    Word count:               perl -ane "$c += scalar @F; END {print $c}" input.txt
                              perl -ane "$c += $#F; END {print $c}" input.txt
                              perl -0777 -ane "print scalar @F" input.txt
                              perl -0777 -ne "print scalar split" input.txt
    Unique word count:        perl -0777 -ne "foreach (sort split){if ($_ ne $old) {print qq/$_\n/;$old=$_;$c++}} END{print $c}" input.txt
    Duplicate word count:     perl -0777 -ne "foreach (sort split){if ($_ eq $old) {print qq/$_\n/;$old=$_;$c++}} END{print $c}" input.txt
    

    Math

    Add command line numbers: perl -e "print eval join('+', @ARGV)" 5 10 15 20
                              perl -e "foreach (@ARGV) {$c+=$_};print $c" 5 10 15 20
    Add columns (r plus s):   perl -ane "print $F[0]+$F[2];print qq/\n/" input.txt
    Add columns (r thru s):   perl -ane "foreach (@F[0..2]){$c+=$_};print qq/$c\n/;$c=0" input.txt
    Add lines (column 1):     perl -ne "$c+=$_; END{print $c}" input.txt
    Add lines (column n):     perl -ane "$c+= $F[0]; END { print $c }" input.txt
                              perl -lane "print $s += $F[2]" input.txt 
    Increment all numbers:    perl -pe "s/(\d+)/ 1 + $1 /ge" input.txt
    Create random numbers:    perl -e "foreach (1..10) { print int(rand(101)).qq/\n/ }"
    Rot13 Encryption:         perl -pe "tr/A-Za-z/N-ZA-Mn-za-m/; print" input.txt
    Test number for prime:    perl -le "print 'PRIME' if (1 x shift) !~ /^(11+)\1+$/ " 37
    

Author Credits
I've written several of these scripts myself, but many have simply been gathered from
various web sites, then tested and modified slightly to fit my own tastes in coding
syntax. I didn't keep track of where I got the scripts but I'm working now to locate
the original sources so that I can place credit here for the authors. If you think
you're due credit for any of these entries please let me know. Here are sources
that I've verified.

  • Jeremy Mates

If you have any suggestions or corrections, please let me know.