Perl one-liner for beginners !

I often use the following arguments to perl:

  • -e Makes the line of code be executed instead of a script
  • -n Forces your line to be called in a loop. Allows you to take lines from the diamond operator (or stdin)
  • -p Forces your line to be called in a loop. Prints $_ at the end

 

  • This counts the number of quotation marks in each line and prints it
    perl -ne '$cnt = tr/"//;print "$cnt\n"' inputFileName.txt
  • Adds string to each line, followed by tab
    perl -pe 's/(.*)/string\t$1/' inFile > outFile
  • Append a new line to each line
    perl -pe 's//\n/' all.sent.classOnly > all.sent.classOnly.sep
  • Replace all occurrences of pattern1 (e.g. [0-9]) with pattern2
    perl -p -i.bak -w -e 's/pattern1/pattern2/g' inputFile
  • Go through file and only print words that do not have any uppercase letters.
    perl -ne 'print unless m/[A-Z]/' allWords.txt > allWordsOnlyLowercase.txt
  • Go through file, split line at each space and print words one per line.
    perl -ne 'print join("\n", split(/ /,$_));print("\n")' someText.txt > wordsPerLine.txt
  • or in other words, delete every character that is not a letter, white space or line end (replace with nothing)
    perl -pne 's/[^a-zA-Z\s]*//g' text_withSpecial.txt > text_lettersOnly.txt
  • perl -pne 'tr/[A-Z]/[a-z]/' textWithUpperCase.txt > textwithoutuppercase.txt;
  • Print only the second column of the data when using tabular as a separator
    perl -ne '@F = split("\t", $_); print "$F[1]";' columnFileWithTabs.txt > justSecondColumn.txt
  • One-Liner: Sort lines by their length
    perl -e 'print sort {length $a <=> length $b} <>' textFile
  • One-Liner: Print second column, unless it contains a number
    perl">perl -lane 'print $F[1] unless $F[1] =~ m/[0-9]/' wordCounts.txt