LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to read a file inside AWK? (https://www.linuxquestions.org/questions/programming-9/how-to-read-a-file-inside-awk-874908/)

NabiVakili 04-13-2011 11:07 PM

How to read a file inside AWK?
 
I want to read content of a file inside a gawk script.
I know that by using "gawk -f filename" I can read a file, but I want to do that inside the script.

How can I do that?

penguiniator 04-13-2011 11:33 PM

From google:"gawk read file":

http://web.mit.edu/gnu/doc/html/gawk_5.html#SEC29

getline < file

grail 04-14-2011 02:38 AM

When you say inside a script ... are you talking inside an awk script or inside a shell script?

jschiwal 04-14-2011 02:51 AM

Look at the manpage of awk. "awk -f awkscript"
The filename argument after the -f option is the awk script to run, not the file or files to scan.

Awk reads the file(s) in the argument, or from the pipe input. That is how it works. If you need to explicitly read a lines from a file, look at "getline()" in the gawk info file. This is an advanced usage that you probably don't need.

I'd highly recommend downloading the pdf version of the gawk manual "Gawk: Effective Awk Programming": www.gnu.org/software/gawk/manual/gawk.pdf

kurumi 04-14-2011 03:18 AM

to read one line from a file, use
Code:

getline < "file"
to read a file from inside awk
Code:

awk 'BEGIN{
  while(( getline line<"file") > 0 ) {
    print line
  }
}


NabiVakili 04-15-2011 11:01 PM

got it!
thanks all...

I want to read a file inside an awk script, and I used "getline < file", it works.

grail 04-16-2011 02:22 AM

You do also realise you can pass as many file names as you like directly to your script?
Code:

awk '<do stuff>' file1 file2 ...

audriusk 04-17-2011 03:44 PM

When I needed to write self-contained AWK script that would process the same file each time it was invoked (say, from /proc filesystem), I did the following:

Code:

#!/usr/bin/awk -f

BEGIN {
    # ARGV[0] is the filename of the script itself.
    ARGV[1] = "/path/to/file"
    # Set ARGV length.
    ARGC = 2
}

This way it behaves as if the file was provided as command line argument.

Should work for more than one file, but I haven't tried that.


All times are GMT -5. The time now is 09:54 PM.