Search code examples
pythoncomparisonawklazy-evaluation

Could a bored AWK master kindly convert this Python program?


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()

Solution

  • 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