We have moved to www.dataGenX.net, Keep Learning with us.

Thursday, March 22, 2012

Perl 1 liners : tips & tricks : Part -2

Here we continues the Perl one liner's magic.......
you can find Perl 1 liners : tips & tricks : Part -1 here.

11. Invert the letter case.

perl -ple 'y/A-Za-z/a-zA-Z/' file_name

This one-liner uses the y operator (also known as troperator). Operators y and tr do string transliteration.Given y/SEARCH/REPLACE/, the operator transliterates all occurrences of the characters found in SEARCH list with the corresponding (position-wise) characters in REPLACE list. Here all caps letters are replaced with small letters and vice-versa.

12. Search and replace in a file.

perl -i -pe 's/1/One/' file_name

Here 1 is replaced with One in the file for 1st occurence only. This is equivalent to the sed command on UNIX systems.

13. Substitute (find and replace) "Dialog" with "Proquest"on lines that matches "IBM".

perl -pe '/IBM/ && s/Dialog/Proquest/' file_name

This one-liner is equivalent to:

while (defined($line = <>)) {
    if ($line =~ /IBM/) {
        $line =~ s/Dialog/Proquest/;

14. Print lines that are 80 chars or longer.

perl -ne 'print if length >= 80' file_name

This one-liner prints all lines that are 80 chars or longer.

15. Print only line selected line or print all lines expect particular line.

perl -ne '$. == 13 && print && exit' file_name

The $. special variable stands for "current line number".This 1 liner prints 13 line of file.

perl -ne '$. != 27 && print' file_name

Prints all the lines expect 27.

16. Print all lines between two regexes (including lines that match regex).

perl -ne 'print if /regex1/../regex2/' file_name

Here it prints all the lines between the 2 regex-es.

17. Print all lines that contain a only number.

perl -ne 'print if /^\d+$/' file_name

18. Print all lines that contain only characters.

perl -ne 'print if /^[[:alpha:]]+$/ file_name

19. Print all lines that repeat.

perl -ne 'print if ++$a{$_} == 2' file_name

This one-liner keeps track of the lines it has seen so far and it also keeps the count of how many times it has seen the line before. If it sees the line the 2nd time, it prints it out because ++$a{$_} == 2 is true. If it sees the line more than 2 times, it just does nothing because the count for this line has gone beyond 2 and the result of the print check is false.

20. Print all the lines if strings in it looks like an email address.

perl -ne 'print if/.+@.+\..+/' file_name

Prints all the lines containing email address.

Enjoy the Simplicity.........

No comments :

Post a Comment