Top fifteen Perl one liners

Following are 15 Perl one liners that are I have found the most useful.

1. To search for word Linux in all files under /etc/

perl -wnl -e '/Linux/ and print;' /etc/* 

2. To see matching 5 digits number in file called members

perl -wnl -e '/\b\d\d\d\d\d\b/ and print $&;' members # 5-digits

3. Print lines from file that has text in it

perl -wnl -e '/^$/ or print;' reports.txt

4. Look for word (\b \b for word boundary) George in files addresses and clients files ignoring case (i)

perl -wnl -e '/\bGeorge\b/i and print $ARGV and close ARGV;' addresses clients

5. Search for word BRIBE, ignoring case, and print the entire paragraph

perl -00 -wnl -e '/\bBRIBE\b/i and print;' lawyer_report.txt

6. Print line number 10 in file named filename

perl -wnl -e '$. == 10 and print;' filename

7. Replace Sep with September in all files under /var/www/html/

perl -i.bak -wpl -e 's/\bSep\b/TSeptember/ig;' /var/www/html/*

8. Match anything that starts with a digit in file ‘data’ and print the whole line

perl -wnl -e '/^\d/ and print $.;' data

9. Look for string ‘File does not exist for entries between Jul 20 and Aug 26′ and print them.

perl -wnl -e '/Jul 20/ ... /Aug 26/ and /File does not exist:/ and print;' error_log

10. Find any file in home directory that is named either game or has sports in its name or whose name starts with word baseball

find $HOME -type f -print | perl –wnlaF'/' -e '-T and $F[-1] =~ /^game$|sports|^baseball/ and print

11. The following deletes the first 10 lines from file named todos.txt

perl -i.old -ne 'print unless 1 .. 10'  todos.txt

12. This will delete all lines except those between Chapter 1 and Chapter 2 from file book.txt

perl -i.old -ne 'print unless /^Chapter 1$/ .. /^Chapter 2/'  book.txt

13. It will convert html to text by removing all tags

cat index.htm | perl -ne 's/\<[^<]*\>//g ;print $_'

The last two taken from (taken from http://sial.org/howto/perl/one-liner/#s3.3)

14. To add #!/bin/bash to start of all *.sh files in the current directory, use

 perl -i -ple 'print q{#!/bin/bash} if $. == 1; close ARGV if eof'   *.sh

15. To remove first four lines from called test.txt

 perl -nle 'print unless 1 .. 4'  test.txt

 

 

2 Responses to “Top fifteen Perl one liners”

  1. Ydo Says:

    Hmm, looks to me 11 and 15 are actually the same.
    And 3 and 8 would be quicker with
    3. grep -v ^$ report.txt
    8. grep ^[0-9] data
    but then again, I’m not that into perl for these kind of operations. I’m a big awk and sed fan…

  2. MIchael Says:

    If I were using this:
    perl -wnl -e ‘/Linux/ and print;’ /etc/*
    How can I print, instead of all the code inside the file, but all the directories and filenames where its found?

Leave a Reply