Passing argument to awk

I'm trying to search through a set of files and extract paragraphs. I have a script that works just fine from the command line but cannot get it to work using 'Execute Shell Script'.

The 'echo' command works, so I believe the variable is passing just fine, but there's something about the awk command this is stopping it from working correctly.

The following works fine if I open terminal and paste this in (using KM):

awk 'tolower($0) ~ /%Variable%SearchQuery%/' RS= ORS="\\n\\n**********************\\n\\n" [^Ω#]* > "Ω Buffer.txt"

Also, the original macro works if I replace $KMVAR_SearchQuery with any word (so hardcoding the search query).

Any help would be amazing.

Read the section in the Execute a Shell Script documentation (which you can get to by selecting Help from the gear menu) on Quoting Strings.

The primary reason for your problem is that you are quoting the parameter to awk in single quotes (') which do not interpolate shell variables. The Quoting Strings section explains some solutions.

Also, this StackOverflow:

is helpful for describing how to use shell variables in awk.


Thanks Peter, that topic is very helpful.
Here's an example Macro that uses that technique:

Example Output


MACRO:   Using KM Variables with Bash awk [Example]

~~~ VER: 1.0    2019-11-25 ~~~
Requires: KM 8.2.4+   macOS 10.11 (El Capitan)+
(Macro was written & tested using KM 9.0+ on macOS 10.14.5 (Mojave))

DOWNLOAD Macro File:

Using KM Variables with Bash awk [Example].kmmacros
Note: This Macro was uploaded in a DISABLED state. You must enable before it can be triggered.

Shell Script

echo | awk -v env_var="$KMVAR_My_KM_Variable" '{print "The value of My_KM_Variable is: \""env_var"\""}'
1 Like

Thank you both!!! That solved it.
For anyone curious, here's my working script:

cd /Users/davideiffert/Dropbox/Messx/Messx\ Workspace/1\ Messx\ Manuscript
awk -v env_var="$KMVAR_SearchQuery" 'tolower($0) ~ env_var' RS= ORS="\\n\\n**********************\\n\\n" [^Ω#]* > "Ω Buffer.txt"

Thanks again @peternlewis @JMichaelTX - You guys are the best.

1 Like