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!

-v inFile[1]=file1.txt (use arrays with -v option)

Status
Not open for further replies.

bitnip

Programmer
Sep 19, 2012
3
US
hey guys, i just joined. Looks like cool community, thanks in advance.


I have an AWK script, "awk.prog", that I launch with a text file that looks like this:

awk -f awk.prog -v inFile1=file1.txt -v inFile2=file2.txt -v inFile3=file3.txt .
.
.
...etc...

and then in the AWK script I have this:

Code:
readFile(inFile1);
readFile(inFile2);
readFile(inFile3);

function readFile(file)
{
  while(  (getline < file) > 0)
  ...
}


I would much prefer to do it somehow like this:

awk -f awk.prog -v inFile[1]=file1.txt -v inFile[2]=file2.txt -v inFile[3]=file3.txt ...etc....

and have the AWK script like this:

Code:
for(a=0; a<number_of_inFiles; a++)
{
  readFile(inFile[a]);
}

Is there some way to do this? ...to pass the "file*.txt" filenames to the AWK program thru an array as I've done above? In actuality I am passing 50+ variables to my AWK program using the -v parameter, including ~25 input filenames. Thanks for any help.
 
Why not use awk -f awk.prog file1.txt file2.txt file3.txt, then they will be ready for you in the ARGV array.

(note that you will need to remove them from the ARGV array manually as you process them if you want to prevent awk from processing them as normal input files)

For example:

Code:
awk 'BEGIN { for (i=1;i<ARGC;i++) print ARGV[i] }' file1.txt file2.txt file3.txt

Annihilannic
[small]tgmlify - code syntax highlighting for your tek-tips posts[/small]
 
Thanks! I'm pretty sure I tried this before but didn't know about "need to removed them from the ARGV array"... so it didn't work properly. But yeah, this seems to work:


Code:
BEGIN {

  for(i=1; i<ARGC; i++)
  {
    inFile[i] = ARGV[i];    # assign filenames to array
    delete ARGV[i];         # remove from ARGV
  }

}

...and now I can access the input files thru their names stored in the array. Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top