Perl Oneliners
One-liners
One-liner: print
- -e|command line
- -E
perl -e "print 42"
perl -E "say 42"
perl -E "say q(hello world)"
One-liner: Rename many files
-
rename
-
glob
-
Rename every .log file adding an extra extension of .old
perl -e "rename $_, $_ . '.old' for glob '*.log'"
- Rename every .log file replacing .log with a timestamp
perl -e "$t = time; rename $_, substr($_, 0, -3) . $t for glob '*.log'"
One-liner: grep on Windows as well
Lacking grep on Windows, search for all the occurrences of the 'secret' in my xml files.
In a single file:
perl -ne "print $_ if /secret/" main.xml
As Windows does not know how to handle wildcards on the command line,
we cannot supply *.xml
and expect it to handle all the xml files.
We help it with a small BEGIN
block. $ARGV
holds the name of the current file
perl -ne "BEGIN{ @ARGV = glob '*.xml'} print qq{$ARGV:$_} if /secret/"
One-liner: Replace a string in many files
- -i
- -p
You have a bunch of text files in your directory mentioning the name:
"Microsoft Word"
You are told to replace that by
"OpenOffice Write"
perl -i -p -e "s/Microsoft Word/OpenOffice Write/g" *.txt
-i = inplace editing
-p = loop over lines and print each line (after processing)
-e = command line script
One-liner: Change encoding
- -i
- -M
- -p
- Encode
Convert all the .srt files that are Windows Hebrew encoded to UTF-8 keeping a backup copy of the original file with a .bak extension.
-i - inplace editing
.bak - generate backup with that extension
-M - load module as 'use' would do
-p - go over line by line on the file, put the line in $_, execute the
command on it and then print the result.
In case of inplace editing, save it back to the file.
perl -i.bak -MEncode -p -e "Encode::from_to($_, 'Windows-1255', 'utf-8')" video.srt
use Encode;
foreach $file (@ARGV) {
copy $file, "$file.bak";
}
while (<>) {
Encode::from_to($_, 'Windows-1255', 'utf-8');
print $_;
}
One-liner: print the 3rd field of every line in a CSV file
- CSV
- -n
- -a
- -F
You have a number of csv files, you want to print the 3rd field of each row of each file.
perl -n -a -F, -e 'print "$F[2]\n"' *.csv
-n = loop over lines but do NOT print them
-a = autosplit by ' '
-F, = replace the split string by ','
You want to make sure all the rows are 4 elements long. Print out file name and line number of all the bad rows.
perl -a -F, -n -e 'print "$ARGV:$.\n" if @F != 4' data.csv
One-liner: Print all usernames from /etc/passwd
perl -n -a -F: -e 'print "$F[0]\n"' /etc/passwd