Perl Oneliners

· jswank's blog


These are Perl implementations of the examples used in Awesome awk oneliners. See perl1line.txt for a very educational set of Perl code in this vein.

Replace multiple spaces with single space #

command | awk '{ gsub(/[ ]+/," "); print }'  # awk
command | perl -pE 's/\s+/ /g'               # perl

Explanation #

Trim leading and trailing spaces #

command | awk '{ gsub(/^[ \t]+|[ \t]+$/, ""); print }'  # awk
command | perl -pE 's/^\s+|\s+$//g'                     # perl

Explanation #

Replace string with another one only in lines containing specific string #

command | awk '/,/{gsub(/ /,""); print}'   # awk
command | perl -pE 'if (m/,/) { s/ //g }'  # perl
command | perl -pE 'if (/,/) { s/ //g }'   # perl - remove optional m
command | perl -pE 's/ //g if (/,/)'       # perl - even more concise

Explanation #

command | awk -F, '(tolower($6)~"rhel" || tolower($6)~"linux"){print $0}'  # awk
command | awk -F, '(tolower($6)~"rhel|linux"){print $0}'  # awk
command | perl -F, -naE 'print if ($F[5] =~ /rhel|linux/i)'  # perl

Explanation #

Example #

$ { cat <<EOF
1,2,3,4,5,6,7
1,2,3,4,5,rhel,6,7
1,2,3,4,5,Linux,6,7
EOF
} | perl -F, -naE 'print if ($F[5] =~ /rhel|linux/i)'
1,2,3,4,5,rhel,6,7
1,2,3,4,5,Linux,6,7
command | awk -F, '{print $1,$2,$7}'               # awk
command | perl -F, -naE 'print "$F[0],$F[1],$F[6]\;n' # perl

Explanation #

$F[0], $F[1], $F[6] specifies the 1st, 2nd, and 7th column of the line

Replace first occurrence of string #

command | awk '{sub(/,/,"1,")}1'  # awk
command | perl -pE 's/,/1,/'      # perl

Example #

1$ echo "foo,bar,baz" | perl -pE 's/,/1,/'
2foo1,bar,baz

Replace last occurrence of string #

command | rev | awk '{sub(/,/,"1,")}1' | rev # awk
command | rev | perl -pE 's/,/1,/' | rev     # perl
command | perl -pE 's/(.*),/${1},new-text/'         # perl - no other commands required

Explanation #

The final example does more with regular expressions.

Example #

1$ echo "foo,bar,baz" | rev | awk '{sub(/,/,"1,")}1' | rev 
2foo,bar,1baz
3$ echo "foo,bar,baz" | perl -pE 's/(.*),/$1,new-text/'
4foo,bar,new-textbaz