jonny789
jonny789

Reputation: 343

redirect to a variable storing awk in 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 }'

Upvotes: 3

Views: 156

Answers (3)

anubhava
anubhava

Reputation: 785256

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

Upvotes: 1

e0k
e0k

Reputation: 7161

Why not just do something like:

File: getlist

#!/bin/sh
if [ "$1" = "f" ]; then
    awk '$5=="f"{print $2,$3}' list.txt
else
    awk '{print $2,$4,$5}' list.txt
fi

If this file is executable, you can call it like:

$ ./getlist f
apple 4
orange 5
grapes 10
$ ./getlist
apple 30 f
potato 40 v
orange 10 f
grapes 8 f
$

Or if you want to specify the search value on the command line:

#!/bin/sh
if [ "$1" ]; then
    awk -v t="$1" '$5==t{print $2,$3}' list.txt
else
    awk '{print $2,$4,$5}' list.txt
fi

This way, you can list fields labelled f or v:

$ ./getlist
apple 30 f
potato 40 v
orange 10 f
grapes 8 f
$ ./getlist f
apple 4
orange 5
grapes 10
$ ./getlist v
potato 2
$ 

Upvotes: 1

Arton Dorneles
Arton Dorneles

Reputation: 1709

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

Upvotes: 1

Related Questions