cat list.txt
1 apple 4 30 f
2 potato 2 40 v
3 orange 5 10 f
4 grapes 10 8 f
Script : getlist ::
if [[ "$@" == *[f]* ]] ; then
awkv1 = $(grep f | awk '{ print $2 $3 }')
else
awkv1 = $(awk '{ print $2 $4 $5 }')
fi
cat list.txt | $(awkv1)
I have a variable awkv1 that stores value depending on argument 'f'.
But it is not working .
Running :: getlist f doesn't do anything.
It should work like this ::
If 'f' is passed in argument then :: cat list.txt | grep f | awk '{ print $2 $3 }'
otherwise :: cat list.txt | awk '{ print $2 $4 $5 }'
Storing partial command line in a string variable is error-prone better to use bash arrays.
You can tweak your script like this:
#!/bin/bash
# store awk command line in an array
if [[ "$*" == *f* ]]; then
awkcmd=(awk '/f/{ print $2, $3 }')
else
awkcmd=(awk '{ print $2, $4, $5 }')
fi
# execute your awk command
"${awkcmd[@]}" list.txt
There are some corrections you need to perform in your script:
awkv1 = $grep f use grep 'f$'. This approach matches the character f only in the last column and avoids fruits with the letter f, e.g. fig, being matched when the last column ends with v. cat list.txt | $(awkv1) by echo "$awkv1" since the output of the previous command is already stored in the variable $awkv1.The corrected version of script:
if [[ "$@" == *[f]* ]] ; then
awkv1=$(grep 'f$' | awk '{ print $2, $3 }')
else
awkv1=$(awk '{ print $2, $4, $5 }')
fi
echo "$awkv1"
You can invoke this script this way: cat list.txt | getlist f
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