quoll faq perl

Faq perl

Posted on Posted in Faq

Extract all public GPG keys from a file

Suppose you have a file named “file-with-keys-gpg” and want to extract it by deleting any other line in the file.

perl -ne 'print if /-----BEGIN PGP PUBLIC KEY BLOCK-----/../-----END PGP PUBLIC KEY BLOCK-----/' file-with-keys-gpg

Of course by extrapolating the logic we might want to print all the lines between two regexp

perl -ne 'print if /regex1/../regex2/' file.txt

Add 1 to all numbers on a string

$str =~ s/(\d+)/$1+1/ge

Number a text file

Suppose we have a text file (prova.txt) that we want to number. We can use:

perl -pe '$_ = "$. $_"' prova.txt

If you want to simulate the output of cat -n prova.txt just use:

perl -ne 'printf "% 5d %s", $., $_' prova.tx

To remove the numbering we can use:

perl -pe 's/^\s*\d+\s*//' prova.txt

Encode/decode a file or string in Mime Base64

Suppose you have a “test encode” string and a “prova.txt” file you want to encode in Mime base64. To solve the problem we can simply launch the command line:

perl -MMIME::Base64 -e 'print encode_base64("test encode")'
perl -MMIME::Base64 -0777 -ne 'print encode_base64($_)' prova.txt

For the reverse operation just do:

perl -MMIME::Base64 -le 'print decode_base64("string in base64")'
perl -MMIME::Base64 -ne 'print decode_base64($_)' prova.base64

 

Just print line 25 of a file

Suppose you only want to print a single line of a file, which for convenience is indicated by line 25

perl -ne '$. == 25 && print && exit' file.txt

Of course if we also want to print lines 31 and 57

perl -ne '($. == 25 || $. == 31 || $. == 57) && print' file.txt

While we wanted all the lines between 25 and 57 included

perl -ne 'print if $. >= 25 && $. <= 57' file.txt

Rename a group of files based on a regex

Suppose you want to rename the name of a group of files that have the following template:

file1_tmp.sh
file2_tmp.sh
...
file99_tmp.sh

and suppose you want to remove the ‘_tmp’ middle part in all the files. We can use the command “rename” or “prename”:

 rename 's/_tmp//' *.sh

 

How to count the number of times a single character is present in each line of a file

Let’s suppose we have a text file named “file.csv” and want to count for each line the number of times a character is displayed, such as the character “,“.
Suppose the result is the output of the same file “file.csv” preceded in each line by the count itself.

Just simply the following single line perl:

perl -ne '@c=$_=~/;/g; print scalar(@c)." ". $_;' file.csv

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *