OSETC TECH

Linux/Awk: Print Filename

This post will guide you how to print filename with awk tool in Linux. How do I print multiple filenames with Awk tool under CentOS/RHEL/Ubuntu Linux.

Print Filename with Awk


If you want to print the filename with awk tool, you just need to use the print command in the awk script, and then pass FILENAME variable to print. Like this:

# awk '{print FILENAME}' /etc/passwd

Outputs:

[root@devops ~]# awk '{print FILENAME}' /etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd
/etc/passwd

If you just want to print one line of filename in the awk prompt, just type the following awk command:

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

Outputs:

[root@devops ~]# awk 'FNR ==1{ print FILENAME }' /etc/passwd
/etc/passwd

Print multiple Name with Awk


You can pass a filename with wildcard to AWK command, and so it will print all filename match the pattern. Type the following command:

# awk '{ print FILENAME; nextfile } ' /root/*.sh

Outputs:

[root@devops ~]# awk '{ print FILENAME; nextfile } ' /root/*.sh
/root/fio1.sh
/root/fio2.sh
/root/test1.sh
/root/test2.sh