Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing filenames to awk

Status
Not open for further replies.

nashcom

MIS
Apr 12, 2002
91
GB
Hi

I’m having a bit of trouble writing my first Unix script.

I’ve written a script which includes some awk coding to extract certain information from a file. The filename is hard-coded into the awk routine. The script is working okay, but what I’d like to do is to have all the files in a directory passed to the script, and if the names match particular criteria then have my awk lines process them. It sounds simple, but I can’t get my head around it!

I’d like everything to happen in the script (ie don’t pass the directory listing as arguments to the script). However, I’ve also tried command line permutations such ‘ls | awk ‘{print $9;}’ | myscript which I thought might pass the filenames into my script, but I’m not sure how to read them from within the script, or even if it’s possible.

Thanks very much.




 
Passing the filenames to be processed as arguments to the script would be the normal way of doing this, so I'm not sure why you prefer not to do it that way?

Doing it the way you describe would work, however no need for the awk '{print $9}' if you are just using the short form ls.

This example would add all of the filenames to a "files" array which you could then process in the END clause.

Code:
ls | awk '
    { files[++maxix]=$1 }
    END {
        for (ix=1;ix<=maxix;ix++) {
            # process input file files[ix] here
        }
    }
'

Or you could of course just process each file as the filename is read.

Annihilannic.
 
Thanks very much for that.

I did manage to get it working by separating out the awk code into its own file, and calling it using a system call from within the bash script and passing it the filename. I was then able to use the FILENAME variable within the awk script. It seems to work fine, but I’ll also experiment with a version based on your code.

Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top