Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run awk file from shell script without specifying awk's exact location

Tags:

linux

shell

awk

I'm trying to debug a shell script that calls an awk file. Which is a nightmare, cause I've never used either before, nor am I very fluent with linux, but anyway

A dev made an awk file and is trying to run it in a shell script.

To try and run it from a separate location, without needing to specify the exact location, they put the awk script in a folder that's in the PATH variable. So that awk file should be available everywhere, right?

When you run it like this...

awk -f script.awk arg1

...can awk find that script? It spits out an error, when the shell script tries to run that awk command:

awk: fatal: can't open source file `script.awk' for reading (No such file or directory)

like image 713
CrazyPenguin Avatar asked Aug 26 '11 15:08

CrazyPenguin


People also ask

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.

How do you run an awk script on a file?

Use either ' awk ' program ' files ' or ' awk -f program-file files ' to run awk . You may use the special ' #! ' header line to create awk programs that are directly executable. Comments in awk programs start with ' # ' and continue to the end of the same line.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

Can awk edit in place?

Overview. Both the awk command and the sed command are powerful Linux command-line text processing utilities. We know that the sed command has a handy -i option to edit the input file “in-place”. In other words, it can save the changes back to the input file.


2 Answers

As you know, awk can't find the script itself.

If the script is marked as executable, and if you have a which command, then you should be able to do:

awk -f `which script.awk` arg1

Alternatively, and probably better, make the script into an executable:

#!/usr/bin/awk -f 
BEGIN { x = 23 }
      { x += 2 }
END   { print x }

The shebang needs the '-f' option to work on MacOS X 10.7.1 where I tested it:

$ script.awk script.awk
31
$

That gives you a self-contained single-file solution.

like image 161
Jonathan Leffler Avatar answered Nov 17 '22 14:11

Jonathan Leffler


No, that's not going to work. awk needs the path to the script to run, it won't use the PATH variable to find it. PATH is only used to find executables.

like image 45
Julian Avatar answered Nov 17 '22 16:11

Julian