1748195 Members
4632 Online
108759 Solutions
New Discussion юеВ

Re: awk help PLEASE

 
SOLVED
Go to solution
David Gwin_1
Advisor

awk help PLEASE

You know... I THOUGHT that I was pretty good at programming in awk until THIS!!! And maybe I just don't know the right function.

Anyhow, all I'm trying to do is determine if a file already exists. I read that the "ls /Backups" command (or any getline cmd) will only execute ONE time (I was thinking that it would execute once for each input record, WRONG).

My real question is... How do i determine if a file already exist without getting an error or system error.


BEGIN { }
{
x=0
while ("ls /Backups" | getline fl)
{
print fl " == " $1 " and x is " x
if ( test fl == $1 ) x=1
}
if (x == 0)
{
print x
system("mkdir /Backups/" $1 )
}
}

THANK YOU
David
7 REPLIES 7
A. Clay Stephenson
Acclaimed Contributor

Re: awk help PLEASE

Use a variation on this theme (the key is redirecting stderr so you don'tt see any errors):

{
x = 0
while ((x < 1) && "ls /Backups 2>/dev/null" | getline fl)
{
++x
}
if (x < 1)
{
print "File not found"
}
else
{
print "File found"
}
}
If it ain't broke, I can fix that.
David Gwin_1
Advisor

Re: awk help PLEASE

Not there... The line
while ("ls /Backups" | getline fl)
ONLY happens one time for each input file. The problem is when there is more than one line in an input file.

The actual error that I'm trying to avoid is on system mkdir command. Although it works without displaying an error, I'm not too thrilled with
system("mkdir /Backups/" $1 " 2>/dev/null")
c_51
Trusted Contributor
Solution

Re: awk help PLEASE

to test for the directory

you could do:

a=system("test -d /tmp");

a=0 if there is a directory /tmp
a!=0 if there isn't
c_51
Trusted Contributor

Re: awk help PLEASE

and to read everyline for every line of input, do something like this:

while (( "ls /tmp" | getline def ) > 0 ) {
print def;
}
close("ls /tmp");
Hein van den Heuvel
Honored Contributor

Re: awk help PLEASE

I perl you'd do somehting like:

perl -e '$dir = "/Backups/$name"; mkdir ($dir,0777) unless (-d $dir)'

fwiw,
Hein.

Muthukumar_5
Honored Contributor

Re: awk help PLEASE

To make this simply with shell we can do as,

[[ ! -d muthu ]] && mkdir muthu


To do with AWK using your style then,

--- test. awk ---
BEGIN { }
{
x=0
while ("[[ -d muthu ]] && ls muthu"| getline fl)
{
print fl " == " $1 " and x is " x
if ( test fl == $1 ) x=1
}
}
END {
if (x == 0)
{
print x
system("mkdir muthu")
}
}

# awk -f test.awk
0
#

That is all.

Problem you had,

1. Try to do check and create new directory in the END part only.

HTH.
Easy to suggest when don't know about the problem!
Gordon  Morrison
Trusted Contributor

Re: awk help PLEASE

Why be AWKward? ksh will do it:

if [[ -d /Backups ]]
then
echo "Directory /Backups exists"
fi

if [[ -a /Backups/filename ]]
then
echo "filename exists"
fi
What does this button do?