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:

(more…)

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

(more…)

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

(more…)

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
(more…)

Number a text file

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

perl -pe '$_ = "$. $_"' prova.txt
(more…)

Add 1 to all numbers on a string

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

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
(more…)