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!

How do I access more than one file at a time in awk?

Multiple Files with Gawk

How do I access more than one file at a time in awk?

by  marsd  Posted    (Edited  )
This FAQ is for gnu awk so if you are using
an older awk, or possibly even nawk, at least
one technique here probably won't work for you.

Traditionally you could load separate files into awk
through BEGIN actions and awk's associative array
facility.

BEGIN {
while ((getline < filename) > 0) {
array1[x++] = $0
}
close(filename)
etc..
}


You can load more than one file in the begin action
into your arrays. You should always close any files
you open with getline in this manner.

You can also create an array variable in the
global scope awk recognizes and pass it to a
function by name. This is familiar to C coders,
though the mechanism by which it works in awk
is more of a namespace collision than anything
else IMO. Try this example with a commandline
like this: awk -f awkscript *.txt

function fileload(fname,arr, y) {
y=0
while ((getline < fname) > 0) {
arr[y] = $0 ; y++
}
close(fname)
return y;
}

function parray(aname,cnt, dd) {
dd = 0
while (dd < cnt) {
print aname[dd]
dd++
}
}

BEGIN {
myarray[0] = ""

for (x=1 ; x < ARGC ; x++) {
p = fileload(ARGV[x],myarray)
parray(myarray,p)
system("sleep 1")
}
}


All of awk's powerful field separation and text processing facilities are available so you can read just the info
you want into your script from a file in the BEGIN
action.

BEGIN {
while ((getline < filename) > 0) {
array1[$4","$6","$8] = $2
}
close(filename)
}

You can also use gawks ability to concatentate strings
to return a small files contents from a function without
using an intermediate array.
Something like:

function filestring(fname, retval) {

while ((getline < fname) > 0) {
retval = retval "\n" $0
}
close(fname)
return retval
}

Hope this helped someone ;)


Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top