Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi
Can anyone help is there a command in Unix in side the awk function which i can check if the file exist or a dierctory does exist?.
regards,
Raim

awk uses the system function to execute any OS command, and the return code can be captured and checked, as shown below. You can also read in all the output of a system call (very handy).
When I check the code returned from the OS, zero means success. But within awk, a zero expression means false and non-zero means true. If you run the code below, you will see that "one means true".
awk 'BEGIN {
rc=system("test -f myfile")
if (rc==0)
print "exists"
else
print "does NOT exist"if (system("test -f myfile"))
print "does NOT exist"
else
print "exists"if (0)
print "zero means true"if (1)
print "one means true"exit}'

Cool - never tried that.
So to test for a file's existence, one way would be:
awk 'BEGIN {
if (! system("test -f myfile")) print "myfile exists"
else print "myfile does not exist"
}'

Great,
I was wondering the same thing a couple of days earlier.
Can you give me a simple eg as to how to execute simple commands inside awk like ls,echo,etc.
I am pretty confused about that.I don't thing they need the system call.
Thanks

I use the system call when I want to get the success code returned to me. And on that system call, you probably want to control where you send stdout and stderr.
When I want the output of the command returned to me, I use the following construct:
"ls -l file1" | getline
printf "file size is %d bytes\n",$5The above getline goes into $0. Or I can read the output into a named variable:
"echo $HOME" | getline myhome
print myhome

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |