3

I'm trying to run an awk script which calls a bash command and uses the output to filter sonme results.

#!/usr/bin/awk -f

BEGIN {

        cmd = system("ls -la")                                                                                                                    
        cmd | $1 \~ /\[aA\]\[dD\]{2}\[rR\]{eE}\[sS\]{2}/ {print $0}                                                                                        
                                                                                                                                                  
        # Also tried
        $1 \~ /\[aA\]\[dD\]{2}\[rR\]{eE}\[sS\]{2}/ {print $0} cmd
    
        close(cmd)

}
suzkirch
  • 43
  • 4
  • 1
    Does this answer your question? [Calling an executable program using awk](https://stackoverflow.com/questions/14634349/calling-an-executable-program-using-awk) – Ted Lyngmo Aug 31 '23 at 21:02
  • From the awk man page: _system(cmd) : executes cmd and **returns its exit status**_!! This is certainly not what you want here. – user1934428 Sep 01 '23 at 05:48

1 Answers1

6

You don't call system() for that. Change this:

cmd = system("ls -la")                                                                                                                    
cmd | $1 \~ /\[aA\]\[dD\]{2}\[rR\]{eE}\[sS\]{2}/ {print $0}
close(cmd)

to this:

cmd = "ls -la"
while ( (cmd | getline) > 0 ) {
    if ( $1 ~ /[aA][dD]{2}[rR]{eE}[sS]{2}/ ) {print $0}
}
close(cmd)

Also, see

By the way, to do a case-insensitive comparison consider simply:

tolower($1) ~ /address/

instead of putting the upper and lower case of each letter inside a bracket expression [dD] (and it's clearer/simpler without using RE intervals dd vs d{2}).

Ed Morton
  • 188,023
  • 17
  • 78
  • 185