3

Is there a way to put little awk scriptoids on the path?

For example, I have this really useful collation operation:

// collate-csv.awk
FNR > 1 || NR == 1

And I can use it in all sorts of great ways:

xargs -a $(find * -name *.csv) awk -F',' -f collate-csv.awk | ...

The only problem is I don't have a way to call my awk tools from anywhere. With an executable shell script, I can drop it into a bin folder on the path. Is there a mechanism in linux where I can make these non-executable awk source files available from anywhere I go in the filesystem?

(with the qualification that the "mechanism" is not a "why don't you just hit it with a hammer"-style kludge)

2

2 Answers 2

5

In addition to @Roamia's answer you can use AWKPATH variable for a list of directory where to look for collate-csv.awk

AWKPATH=${HOME}/include/awk:/some/other/path
export AWKPATH
xargs -a $(find * -name *.csv) awk -f collate-csv.awk -F',' | ...

please note

  • .awk extension is not mandatory, just be consistent,
  • shebang line e.g. #!/usr/bin/awk -f is mandatory when script is used standalone as a script (no awk -f call),
  • you will have to use awk -f (and awk know how to use AWKPATH, bash don't)
1
  • 1
    You should mention that AWKPATH is an extension to POSIX that's supported by GNU awk, idk about any others. I don't see anything in your script that'd make a shebang mandatory.
    – Ed Morton
    Sep 18, 2020 at 15:23
3

Create an executable awk script and add it to your $PATH

mkdir -p "$HOME/bin"
cat >"$HOME/bin/collate-csv <<'x'
#!/usr/bin/awk -f
#
# collate-csv.awk
#
NR == 1 { print }
FNR == 1 { next }
{print}
x

chmod a+x "$HOME/bin/collate-csv"
export PATH="$PATH:$HOME/bin"

Now you can use collate-csv just as you would any other command

xargs -a $(find * -name *.csv) collate-csv -F',' | ...
2
  • suppose i created a ${HOME}/include/awk and dropped my awk source code in there for more advanced tools. Does awk need any coercion to link the source code to the executables?
    – Chris
    Sep 18, 2020 at 13:53
  • @Chris my proposal is that the awk scripts become executable. So you can put them in any directory you like, add that directory to your $PATH, and they'll be available exactly as any other command. I've chosen "$HOME/bin" because that's what I use everywhere for all my personal scripts and programs. You could just as easily use "$HOME/include/awk"
    – roaima
    Sep 18, 2020 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.