Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect to a variable storing awk in bash

Tags:

linux

bash

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 }'

like image 933
jonny789 Avatar asked Dec 02 '25 09:12

jonny789


2 Answers

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
like image 199
anubhava Avatar answered Dec 04 '25 01:12

anubhava


There are some corrections you need to perform in your script:

  1. Remove spaces of awkv1 = $
  2. Instead of 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.
  3. Replace 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

like image 32
Arton Dorneles Avatar answered Dec 04 '25 01:12

Arton Dorneles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!