To print filename with awk

The syntax is:


awk '{ print FILENAME }' fileNameHere
awk '{ print FILENAME }' /etc/hosts


You might see file name multiple times as awk read file line-by-line. To avoid this problem update your awk/gawk syntax as follows:

awk 'FNR == 1{ print FILENAME } ' /etc/passwd
awk 'FNR == 1{ print FILENAME } ' /etc/hosts

To print filename in BEGIN section of awk

Use the following syntax:


awk 'BEGIN{print ARGV[1]}' fileNameHere
awk 'BEGIN{print ARGV[1]}{ print "someting or do something on data" }END{}' fileNameHere
awk 'BEGIN{print ARGV[1]}' /etc/hosts


However, ARGV[1] might not always work.

So you need to modify it as follows (assuming that ls -l only produced a single line of output):
ls -l /etc/hosts | awk '{ print "File: " $9 ", Owner:" $3 ", Group: " $4 }'


How to deal with multiple filenames specified by a wildcard

Use the following simple syntax:


awk '{ print FILENAME; nextfile } ' *.c
awk 'BEGIN{ print "Starting..."} { print FILENAME; nextfile }END{ print "....DONE"} ' *.conf
Esta resposta lhe foi útil? 2 Usuários acharam útil (18 Votos)