2

Is it possible to set a global separator of awk, e.g., in a .conf file or environment var?

I'm handling lot of files that using customized separator, don't feel right to manually set the FS and OFS every time.

thanks.

StanleyZ
  • 598
  • 6
  • 22

1 Answers1

4

No, best you can do is either export a shell variable and then set FS from that, e.g.:

$ cat tst.awk
BEGIN { FS=ENVIRON["AWK_FS"] }
{ print NF }

$ export AWK_FS=","
$ echo 'a,b,c' | awk -f tst.awk
3

or include a file that sets the FS:

$ cat setFS.awk
BEGIN{ FS="," }

$ cat tst.awk
@include "setFS.awk"
{ print NF }

$ echo 'a,b,c' | awk -f tst.awk
3

The "@include" construct is gawk-specific, see https://www.gnu.org/software/gawk/manual/gawk.html#Include-Files. You still have to put the same code into every script to include that file but at least the actual FS setting (and OFS and whatever else you commonly do) code will only be specified once in that included file.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    I'm using the `@include` solution myself, including a `default.awk` in `~/awk` directory (in which I have code to detect the `FS` automatically based on character frequencies of the usual suspects). You can `export AWKPATH=/home/user/awk`. – James Brown Jan 21 '17 at 12:19
  • `++`, I actually thought of commenting its _NOT_ possible back in the day. A narrow escape! :D – Inian Jan 21 '17 at 15:44
  • 1
    @JamesBrown Note that `@include "setFS.awk"` is longer than `BEGIN { FS = "," }`, from which we can remove spaces, still. `@include` is specific to GNU Awk, also. – Kaz Feb 06 '17 at 15:20