[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How do I determine the existence (or non-existence) of a file from a
From: |
david kerns |
Subject: |
Re: How do I determine the existence (or non-existence) of a file from an AWK script? |
Date: |
Mon, 10 Apr 2023 13:47:31 -0700 |
On Mon, Apr 10, 2023 at 1:40 PM Neil R. Ormos <ormos-lists@ormos.org> wrote:
> Alan Mackenzie wrote:
>
> > Hello, gawk.
>
> > This should be something quite simple, but I
> > can't work out how to do it.
>
> > Given a file name in an AWK script, does a file
> > with that name actually exist? In a shell
> > script, I'd simply do [ -f "$FOO" ]. What do I
> > have to do in AWK?
>
> > The context is a script which checks certain
> > syntactic things in a git commit message. I
> > want to extend it to check that the noted file
> > names in the commit message don't have typos, or
> > missing directory parts, that kind of thing.
>
> You might use something like:
>
> fres=!(system("/usr/bin/test -f " foo));
>
> where foo is an awk variable containing the name of the file.
>
> fres will be 1 if the file exists and is a regular file; otherwise 0. The
> -e test might be appropriate in some cases.
>
> Also, you will want to escape or quote the contents of foo, as required by
> the shell, if foo is not guaranteed to be free of characters special to the
> shell. On my systems, calls to gawk's system() function run /bin/sh. I
> don't know if that's universal on all platforms.
>
> or this: (same warnings about filenames containing space applies)
$ gawk '
function stat(file, cmd, line) {
cmd = "/bin/file " file
cmd | getline line
close(cmd)
return line
}
BEGIN {
print stat("/tmep");
print stat("/tmp");
print stat("/etc/hosts");
}'
/tmep: cannot open (No such file or directory)
/tmp: sticky directory
/etc/hosts: ASCII text