How to cat a file from awk?

file = "a.txt"
system(cat file)

I wish to do something like that? (open a file whose name is in an awk variable).
How is it done?

Asked By: learner


getline is your friend:

awk 'BEGIN{file="a.txt";while ((getline<file) > 0) {print}}'
Answered By: JRFerguson

If what you intend to do is to define the file that should be processed in the awk script itself, you could alter the ARGV array, and the ARGC variable accorgingly :

awk 'BEGIN{ ARGV[ARGC] = "your_file.txt" ; ARGC++} {print}'
Answered By: Vincent Nivoliers

The problem is that system() passes the command line to a shell, so in the general case, you need to escape all shell special characters in the name of the file.

awk has a ENVIRON associative array that is mapped to the environment it received, but unfortunately, assigning to it doesn’t affect the environment of the commands executed via system or getline

awk -v q="'" '
   function escape(str) {
     gsub(q, q "\" q q, str)
     return q str q
   BEGIN {
     file = "a.txt"
     system("cat " escape(file))

Of course, if the file is “a.txt” or you can make sure that its path will never contain any shell special characters, you can get away with:

system("cat " file)

If you can make sure it doesn’t contain single quote characters, you could do:

system("cat '''" file "'''")
Answered By: Stéphane Chazelas
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.