print lines matching a pattern exactly 'n' times
( categories: one liners | regular expressions )The key is to do the match with the 'g' modifier in list context, then compare the result in scalar context to obtain the number of matches.
Example:
Print the lines in 'file.txt' that have the string 'for' repeated exactly 3 times:
perl -ne 'print if ( ( () = /for/g ) == 3 )' file.txt
calculate the total size of a list of files
( categories: one liners | working with files )Use ls -l to get the list of files you want to sum and pipe the result to a perl one-liner that sums the fifth column of every line it processes.
For example, to get the total size of all your .rpm files in your current directory, use the following:
ls -l *rpm | perl -lane '$total += $F[4]; END { print "Total: $total bytes\n" }'
add a line to a file
( categories: one liners )For example, insert the line "New line added!!" in line 100 of example.txt:
perl -pi -le 'print "New line added!!" if $. == 100' example.txt
If you want to insert the same line in multiple files, use the following:
perl -pi -le 'print "New line added!!" if $. == 100; close ARGV if eof' *.txt
('close ARGV if eof' is needed to reset the variable '$.' before processing the next file).
print a range of lines from a file
( categories: one liners )Let's say you want to print from 'file.txt' only the lines 10 to 20:
perl -ne 'print if 10..20' file.txt
check the syntax of a perl script
( categories: one liners )perl -wc script.pl
NOTES:
- The above command just check the syntax, it does not execute the script.
- If you don't want to see the warnings, remove 'w' from the command line arguments.
remove all blank lines of a file
( categories: one liners )Without saving a backup of the previous file:
perl -ni -e 'print unless /^$/' file
Saving the original file as file.bak:
perl -ni.bak -e 'print unless /^$/' file
replace all ocurrences of 'foo' with 'bar' in a file
( categories: one liners )Without saving a backup of the previous file:
perl -pi -e 's/foo/bar/g' file
Saving the original file as file.bak:
perl -pi.bak -e 's/foo/bar/g' file
check the version of installed modules
( categories: one liners | perl modules )To check the version number of a module use the following one-liner: 'perl -M
Example:
#-- check the version number of CGI module
perl -MCGI -e 'print "$CGI::VERSION \n"'
list the directories where perl modules are located
( categories: one liners | perl modules )The array @INC contains the list of places that the 'do EXPR', 'require', or 'use' constructs look for their library files. The following one-liner shows the contents of that array:
perl -e 'foreach $folder (@INC) { print "$folder\n";}'
