RunSingh
RunSingh

Reputation: 69

How to read multiple files from within awk script without passing at command line?

I have an awk script which is called something like this:

awk -f d.awk /var/log/app*.log 

And this works fine. Log file path is constant and not changing (only the number of files changes in this location due to log rotation) so I want to remove it from command line and hard code inside the awk script. Is there a way to skip passing this argument from command line and hard code it within the awk script and still achieve the same result?

I read about getline but it is not working for me. awk script outline is something like this:

BEGIN{
    #Initialization of few variable
}
match() {
    #Main process logic
    # Collect the output
    output=output" " result_after_processing
}
END{
    #Write the output to output file
    print output >> some_output_file
}

Upvotes: 0

Views: 779

Answers (1)

Ed Morton
Ed Morton

Reputation: 203502

BEGIN {
    cmd = "printf \047%s\n\047 /var/log/app*.log"
    while ( (cmd | getline line) > 0 ) {
        ARGV[ARGC++] = line
    }
    close(cmd)
}

should work as long as your file names don't contain newlines.

This is one of those rare cases where use of getline is appropriate - make sure to read http://awk.freeshell.org/AllAboutGetline if you're ever considering using it in future.

Upvotes: 5

Related Questions