UNIX & GNU/Linux - awk - Using the FILENAME variable

With the awk FILENAME builtin variable, we are able to retrieve the name of the file passed as argument during the execution.

It will avoid us to use a regex command line. Sometimes interesting.

Let's see this.

Explanation

In the example below, we're going to retrieve the name of the file used as argument and display it. But only if we are scanning the first line.
For that, we're going to use the FNR variable, also a awk builtin variable, to check where we are.
If we're in the first line, we will display the file name.

Code

customers.txt

Georges William 12-2-1967 M 1895602
John Maynard 7-4-1944 W 981502
Wolfgang Amadeus 3-11-1938 M 64158674102
Ludwig SCHMILL 11-28-1957 M 5648510
Antonio VAVILDA 5-16-1937 M
Hugues Ofrette 8-11-1958 M 4515660
Dagobert ELOY 7-14-1905 M 0225415487

Akio Shamiwara 1-2-1965 n 4
Antonio SZWPRESWKY 16-5-8937 M 0298358745

bp2.awk

#!/bin/awk

# Begin
BEGIN {
    FS=" ";
};

# Dev
{
    if (FNR == 1) {
        print("The name file is:", FILENAME)
    }
    print FNR, $0
}

# End
END {}

Execution

awk -f bp2.awk customers.txt

Output

File name is: customers.txt
1 Georges William 12-2-1967 M 1895602
2 John Maynard 7-4-1944 W 981502
3 Wolfgang Amadeus 3-11-1938 M 64158674102
4 Ludwig SCHMILL 11-28-1957 M 5648510
5 Antonio VAVILDA 5-16-1937 M
6 Hugues Ofrette 8-11-1958 M 4515660
7 Dagobert ELOY 7-14-1905 M 0225415487
8
9 Akio Shamiwara 1-2-1965 n 4
10 Antonio SZWPRESWKY 16-5-8937 M 0298358745

Finally

You've made it.
Well done. cool

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.