i have an awk script that i’m running against a pair of files. i’m calling it like this:
awk -f script.awk file1 file2
script.awk looks something like this:
BEGIN {FS=":"}
{ if( NR == 1 )
{
var=$2
FS=" "
}
else print var,"|",$0
}
the first line of each file is colon-delimited. for every other line, i want it to return to the default whitespace file seperator.
this works fine for the first file, but fails because FS is not reset to : after each file, because the BEGIN block is only processed once.
tldr: is there a way to make awk process the BEGIN block once for each file i pass it?
i’m running this on cygwin bash, in case that matters.
If you’re using
gawkversion 4 or later there’s theBEGINFILEblock. From the manual:For example:
Output:
Edit – a more portable way
As noted by DennisWilliamson you can achieve a similar effect with
FNR == 1at the beginning of your script. In addition to this you could changeFSfrom the command-line directly, e.g.:Here the
FSvariable will retain whatever value it had previously.