manpagez: man pages & more
info gawk
Home | html | info | man

File: gawk.info,  Node: File Checking,  Next: Empty Files,  Prev: Rewind Function,  Up: Data File Management

10.3.3 Checking for Readable Data files
---------------------------------------

Normally, if you give 'awk' a data file that isn't readable, it stops
with a fatal error.  There are times when you might want to just ignore
such files and keep going.(1)  You can do this by prepending the
following program to your 'awk' program:

     # readable.awk --- library file to skip over unreadable files

     BEGIN {
         for (i = 1; i < ARGC; i++) {
             if (ARGV[i] ~ /^[a-zA-Z_][a-zA-Z0-9_]*=.*/ \
                 || ARGV[i] == "-" || ARGV[i] == "/dev/stdin")
                 continue    # assignment or standard input
             else if ((getline junk < ARGV[i]) < 0) # unreadable
                 delete ARGV[i]
             else
                 close(ARGV[i])
         }
     }

   This works, because the 'getline' won't be fatal.  Removing the
element from 'ARGV' with 'delete' skips the file (because it's no longer
in the list).  See also *note ARGC and ARGV::.

   Because 'awk' variable names only allow the English letters, the
regular expression check purposely does not use character classes such
as '[:alpha:]' and '[:alnum:]' (*note Bracket Expressions::).

   ---------- Footnotes ----------

   (1) The 'BEGINFILE' special pattern (*note BEGINFILE/ENDFILE::)
provides an alternative mechanism for dealing with files that can't be
opened.  However, the code here provides a portable solution.

© manpagez.com 2000-2025
Individual documents may contain additional copyright information.