Sometimes, we need to run awk or sed or other scripts inside a shell script. Although scripts usually can be passed to interpreters by argument, this is not easy for any serious scripts that consists of more than a few lines. Yes, you can put scripts in separate script files, but sometimes I don’t want a dozen small files to do a small task.
Here shows some great examples of embedding scripts using here document.
There is another way to do it by extracting the embedded script from the shell script using sed, like this.
Now we can write:
# any shell script awk -f <(sed -n '/^__AWKCODE1__/,/^__AWKCODE1__/p' $0) # any shell script exit 0 # end the script here __AWKCODE1__ # any awk code __AWKCODE1__ # you can have more scripts here
This script will now extract part of itself as an awk script and feed to awk. Here <() is used to get the output of a command and assign a named pipe to it and place the name of the pipe in the command argument of awk -f. The command inside parenthesis is to tell sed to print a particular range of lines bounded by these patterns and suppress output of every other lines (by -n).
In this way, you can put multiple scripts inside the shell script. And since I use emacs, I can change the major mode to awk-mode to edit awk scripts and back to shell-mode afterwards to automatically format the indention and also have syntax highlighting.