Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GAWK Script - Print filename in BEGIN section

I am writing a gawk script that begins

#!/bin/gawk -f
BEGIN { print FILENAME }

I am calling the file via ./script file1.html but the script just returns nothing. Any ideas?

like image 532
jonseager Avatar asked Mar 26 '11 11:03

jonseager


People also ask

How to print FILENAME using awk?

Can I print the name of the current input file using gawk/awk? The name of the current input file set in FILENAME variable. You can use FILENAME to display or print current input file name If no files are specified on the command line, the value of FILENAME is “-” (stdin).

How to display the FILENAME in Unix?

ls - displays file names. ls –l - displays file names with permissions, site, owner, etc.

What is awk '{ print $1 }'?

The awk is a very powerful command or interpreted scripting language to process different text or string data. The awk is generally used to process command output or text or configuration files. The awk provides '{print $1}' command in order to print the first column for the specified file or output.


1 Answers

You can print the file name when encounter line 1:

FNR == 1

If you want to be less cryptic, easier to understand:

FNR == 1 {print}

UPDATE

My first two solutions were incorrect. Thank you Dennis for pointing it out. His way is correct:

FNR == 1 {print FILENAME}
like image 94
Hai Vu Avatar answered Nov 03 '22 09:11

Hai Vu