Showing posts with label regex. Show all posts

Creating a hash in perl with all the regex matches

As i explained here :http://theunixshell.blogspot.com/2013/01/capturing-all-regex-matches-into-array.html about storing each and each regex match in an array,Now let's see how do we store each and every regex match in a hash instead.

Lets say we have text file like below:

hello world 10 20
world 10 10 10 10 hello 20
hello 30 20 10 world 10


I want to store each and every decimal integer here in a hash as a key and count of their occurances in a value for that key.

Below is the solution for that:

perl -lne '$a{$_}++for(/(\d+)/g);END{for(keys %a){print "$_.$a{$_}"}}' Your_file

output generated will be:

> perl -lne '$a{$_}++for(/(\d+)/g);END{for(keys %a){print "$_.$a{$_}"}}' temp
30.1
10.7
20.3






Capturing all the regex matches into an array in perl

Often we need to track the list of matches whenever we use a regex.
for example lets say i have a file which looks like below:

Jan 1 1982
Dec 20 1983
jan 6 1984

Now if i want to store all the decimal number in the file in a array..How?

first thing is we need to use a regex match and store all the numbers into an array.

Below is the code for it :

perl -lne 'push @a,/\d+/g;END{print "@a"}' your_file

The above will output:

> perl -lne 'push @a,/\d+/g;END{print "@a"}' your_file
1 1982 20 1983 6 1984


In the same way you can use any other pattern in the match regex and capture those patterns in an array.