cucurbit
cucurbit

Reputation: 1442

store awk command in a variable of bash script

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 :)

Upvotes: 3

Views: 2618

Answers (2)

mpez0
mpez0

Reputation: 2883

Forget the backticks and parentheses. You just want to store the awk script itself

cmd='/something/ {if ...} {...} END {...}'
awk "$cmd" $input

Upvotes: 5

Ed Morton
Ed Morton

Reputation: 203512

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

Upvotes: 8

Related Questions