Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials

print lines matching a pattern exactly 'n' times

( categories: | )

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: | )

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: )

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: )

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: )

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: )

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: )

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: | )

To check the version number of a module use the following one-liner: 'perl -M -e 'print "$<module>::VERSION \n"'.

Example:

#-- check the version number of CGI module
perl -MCGI -e 'print "$CGI::VERSION \n"'


list the directories where perl modules are located

( categories: | )

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";}'


Syndicate content