Checking existence of file using awk

Hi,

I need to check whether a particular file exists ot not using awk.
Can anyone help me please?
For Example:script that i am using:

awk '{filename =$NF;
rc=(system("test -r filename")) print $rc;}' "$1"

is not working.
Here I am passing a text file as input whose last word contains a filename..
Input File FOrmat

word1 word2 <filename>
word1 word2 word3 <filename>

and so on

Thanks In Advance
Manish

How about this

 awk ' { FN=$NF
   if ((getline < FN) > 0) {
       close(FN);
       print FN " exists and is readable"
    }}' infile

Hi,

Its not working :frowning:
I am using this script:

awk ' { FN=$NF
if ((getline < FN) > 0) {
close(FN);
print FN " exists and is readable"
}
}' "$1"

and i am calling this as <scriptname> <inputfilename>.
Also i need to print message when the file does not exist.
Please help.

You should call the awk statement with the input file, it will extract the filename and check!

--ahamed

---------- Post updated at 07:53 PM ---------- Previous update was at 07:48 PM ----------

Just curious why do you need an awk statement to check the file existence?

--ahamed

File must exist and be > 0 bytes.

Below includes does not exist message:

awk ' { FN=$NF
if ((getline < FN) > 0) {
close(FN);
print FN " exists and is readable"
} else {
  print FN " does not exist"
}}' "$1"

What issue are you getting, are there any error messages?

1 Like

Thanks a lot!! It works now.

---------- Post updated at 02:27 PM ---------- Previous update was at 02:23 AM ----------

Hi,

there is a new requirement in above script.
Apart from input filr a string is also sent as second parameter.
I have to search the filename whether that contains the passed input string or not.
Here is the script that i am using:
#! /usr/bin/ksh
stringtomatch="$2"
awk ' { FN=$NF
if(0!=index($NF,stringtomatch))
{
if ((getline < FN) > 0) {
close(FN);
print FN " exists and is readable"
} else {
print FN " does not exist"
}
}else {
print FN "does not contain string"
}
}' "$1"
Please help.TIA-Manish

awk -v stringtomatch="$stringtomatch" to get the variable inside awk.