Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store awk command in a variable of bash script

Tags:

awk

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

like image 409
cucurbit Avatar asked Jan 22 '26 10:01

cucurbit


2 Answers

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
like image 120
Ed Morton Avatar answered Jan 25 '26 18:01

Ed Morton


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

cmd='/something/ {if ...} {...} END {...}'
awk "$cmd" $input
like image 21
mpez0 Avatar answered Jan 25 '26 19:01

mpez0