简体   繁体   中英

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 }' cat list.txt | grep f | awk '{ print $2 $3 }'

otherwise :: cat list.txt | awk '{ print $2 $4 $5 }' cat list.txt | awk '{ print $2 $4 $5 }'

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 , eg fig , being matched when the last column ends with v.
  3. Replace cat list.txt | $(awkv1) 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 cat list.txt | getlist f

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
$ 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM