views:

120

answers:

2

I love Python but do not really care for AWK. For purposes of comparison (and to see how a Python-to-AWK master would do this), could someone rewrite the following Python program in AWK? Considering how short it is, some would think that the rewrite would be simple and easy for anyone with a little time.

import os

ROOT = '/Users/Zero/Documents/MyProgram.app/Contents/TempFiles'
ID = '628251 173511 223401 138276 673278 698450 629138 449040 901575'.split()

def main():
    for name in os.listdir(ROOT):
        if '.log' in name.lower():
            path = os.path.join(ROOT, name)
            if os.path.isfile(path):
                data = open(path, 'rb').read()
                for line in data.split('\r'):
                    for number in ID:
                        if number in line:
                            print line
                            break

if __name__ == '__main__':
    main()
+6  A: 

Why awk?

This looks like a simple grep command to me; something like:

egrep -w '628251|173511|223401|138276|673278|698450|629138|449040|901575' /Users/Zero/Documents/MyProgram.app/Contents/TempFiles/*.log*

update: or use find+grep, as suggested in some of the comments, if a recursive search is intended

David Gelhar
why awk? see `http://awk.info`
ghostdog74
+4  A: 
BEGIN{
   id="628251 173511 223401 138276 673278 698450 629138 449040 901575"
   m=split(id,ID," ")
   for(i=1;i<ARGC;i++){
       while( (getline line<ARGV[i] ) > 0 ){
           n=split(line,LINE," ")
           for ( o=1; o<=n; o++){
                for(num in ID){
                   if ( num == LINE[o] ){
                     print line
                   }
                }
           }
       }
   }
}

save as myscript.awk , then

#!/bin/bash
ROOT = "/Users/Zero/Documents/MyProgram.app/Contents/TempFiles"
cd $ROOT
awk -f myscript.awk file* #do for files that start with "file"

@OP,

For text/file processing, awk doesn't lose to Perl or Python or any others. If you (or others here thinking awk is obsoleted) are interested, go to http://awk.info. And no, awk still has its uses in the modern environment. don't let anyone tell you otherwise

ghostdog74
Thanks for conversion! I guess it really is just a matter of porting from one language to another. Thanks to everyone else as well who pointed out the usage of `grep`. Being acquainted with *Nix systems and their many tools is obviously superior when working with them.
Noctis Skytower