I'm trying to store an awk command (command, not the result) in a variable. My objective is to use that variable later in the script, with different inputs. For example:
cmd=$(awk '/something/ {if ...} {...} END {...}')
$cmd $input
I've tried to store the command with $() (like in the example), also with backticks ... But I'm not able to achieve it.
I appreciate the help or any suggestion :)
Do not do that, use a function instead of a variable, it's what functions exist to do:
$ cmd() { awk -v x="$1" 'BEGIN{print x}'; }
$ cmd foo
foo
$ cmd bar
bar
A different example:
$ cat file1
a
b
$ cat file2
c
d
e
$ cmd() { awk '{print FILENAME, $0}' "$1"; }
$ cmd file1
file1 a
file1 b
$ cmd file2
file2 c
file2 d
file2 e
Forget the backticks and parentheses. You just want to store the awk script itself
cmd='/something/ {if ...} {...} END {...}'
awk "$cmd" $input
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With