Globbing in scripting languages

Globbing is the most common and yet the most powerful operation that any scripter would use.

glob() is a Unix library function that expands file names using a pattern-matching notation reminiscent of regular expression syntax but without the expressive power of true regular expressions.

All most all the scripting languages has the globbing feature in them, yet here the mail focus in on bash, python, ruby, perl as they are my favs!

Use case : For the simplicity of it, let consider a senario where in we need to work on all the .log files in a given path (/var/log/ in our case) and check if the word ERROR is present in them, if yes print the log name. Assuming (again for making the code less complex and focusing on globbing more) that the user has read permissions on all the log files in that give path.

Globbing in BASH :

Well bash globbing is very simple, yet very powerful!

for log in /var/log/*.log
do
    grep -q 'ERROR' "$log" && echo "$log"
done

Well, the above code is just make it clear on globbing in a loop, but the whole code can be reduced to a single line like : grep -l 'ERROR' *.log

Globbing in Python :

Python needs the famous glob module to be imported.

import glob
for log in glob.glob('/var/log/*.log'):
    with open(log) as f:
        data = f.read()
        if 'ERROR' in data:
            print log

Globbing in Ruby :

Dir['/var/log/*.log'].each do |log|
    puts log if File.open(log).grep(/ERROR/)
end

Globbing in Perl :

use File::Glob qw( bsd_glob );
 
foreach my $log (bsd_glob('/var/log/*.log')) {
   open(my $fh, '<', $log);
   while (<$fh>) {
      if (qr/ERROR/) {
         print  $log;
         last;
      }
   }
}

So, with the file name one can play around with processing them further as per the needs! Happy Hacking!

Share this