awk command to test if a string is a file

What awk command will test a string to determine if it is a valid file name?

With the following awk statement I isolate the lines from the inputfile that might contain a filename, then I attempt to test the possible filename which is always in $4 from each line. However it is not working at all as i do not think the system command gets passed $4 from awk. Have been struggling with this all day

Should be something like this:

if (system("test -r " $4)){
  print $4 " not found"
}
else {
  print $4 " found"
}

Hi Arsenalman!

First of all:

means empty string (literally line which has beginning and end and nothing between them).
Then 'then'. I usually don't use it in awk scripts. My awk gives no error if I put it after 'if'-statement, but I'm not sure that its behavior is correct.
Now your system call:

Obviously you meant, that 'system' will invoke 'ls $4', print the exit code of the command back to awk script and then awk will print it with 'print $0'. It doesn't work such way. :slight_smile:
'system' simply calls a system command and does not return the output of the command to awk. What it returns is....I'll give you three guesses... Yeahh.. The exit code of the invoked command.
so

exit_code=system("ls " $4)

would do in your case, but it is better to use a special shell command which checks whether its argument is a file: 'test -f'. It returns 1 if the tested thing is not a file, and 0 if it is, so we have

exit_code=system("test -f " $4)

now we need to check what the exit code was

exit_code=system("test -f " $4)
if (exit_code) # condition in brackets which isn't 0 or Empty means TRUE
                   # in our case exit_code would be 1 if file does not exist
   print $4 " is not a file"
else
   print $4 " is a file"

You can do it even smarter. You don't need to store the exit code in an explicit variable. You can use 'system' straight in your 'if' condition:

if ( system("test -f " $4) )
   print $4 " is not a file"
else
   print $4 " is a file"

I hope I could help

Franklin52, sidorenko thank you both for your valuable input, it has help me take further today, still no cigar. Will definitely post when I hit jack pot or getting close and need a little more guidance.

Finally hit the jack pot. again thank you for your contribution which help me move forward along to my destination:

{
if (sub(/DISCOVERY=ON/, "DISCOVERY=OFF"))
print $0
if ( $1 ~ /^#/ ) {
        print $0 }
if ( NF == 4 ){
    if ( system("test -d " $4) ) {
         }
    else {
        print "1        0       0       "$4 "\n" }
}
}