Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Multiple Files with Gawk

How do I access more than one file at a time in awk? by marsd
Posted: 13 Oct 02 (Edited 12 Nov 03)

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

   while ((getline < filename) > 0) {
      array1[x++] = $0

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) {
   while ((getline < fname) >  0) {
          arr[y] = $0 ; y++
return y;

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

    for (x=1 ; x < ARGC ; x++) {
        p = fileload(ARGV[x],myarray)
        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

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

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
    return retval

Hope this helped someone ;)


Back to AWK FAQ Index
Back to AWK Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close