FAQs
Using simple arrays in bash
With Bash to explicitly declare an array you have to use
declare -A mioarray
To have the value of element 5 just write
echo ${mioarray[5]}
(more…) Redirect the standard error to the standard output
To redirect the standard error of a shell command, just use the following syntax:
ls file-that-does-not-exist 2>&1 | grep file
Or even better not to have on the terminal the standard error just throw it in /dev/null
(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…)