Change FS to AWK for multiple files

I am trying to read multiple files in an AWK script, but when changing between files, I also need to change the field separator (FS). At the moment, I have received:

FILENAME=="A.txt"{
    FS=";"
    //DoSomething
}
FILENAME=="B.txt"{
    FS=" - "
    //DoSomething
}

But, as you know, FS will not be configured correctly for the first line of the file. How can i solve this?

+4
source share
2 answers

You can specify field separators on the command line:

awk -f a.awk FS=";" A.txt FS=" - " B.txt

Thus, the field separator will change for each file. From http://www.delorie.com/gnu/docs/gawk/gawk_82.html :

Any awk variable can be set by including variable assignment among arguments on the command line when awk is called

and

awk-, .

+9

, @HakonHaegland, FS arg, . .

, (, * ), BEGINFILE, GNU awk, $0 FS, awk . :.

$ cat file
a-b-c
d e f

$ awk '{print NF, $1}' file
1 a-b-c
3 d

$ awk '{FS="-"; $0=$0; print NF, $1}' file
3 a
1 d e f

, ( FNR==1).

+6

Source: https://habr.com/ru/post/1539900/


All Articles