简体   繁体   中英

bash/ksh grep script take more than one argument

   #!/bin/ksh
if [ -n "$1" ]
then
    if grep -w -- "$1" codelist.lst
    then
        true
    else
        echo "Value not Found"
    fi
else
    echo "Please enter a valid input"
fi

This is my script and it works exactly how I want at the moment, I want to add if I add more arguments It will give me the multiple outputs, How can I do that?

So For Example I do./test.sh apple it will grep apple in codelist.lst and Give me the output: Apple

I want to do./test.sh apple orange and will do: Apple Orange

You can do that with shift and a loop, something like (works in both bash and ksh ):

for ((i = $#; i > 0 ; i--)) ; do
    echo "Processing '$1'"
    shift
done

You'll notice I've also opted not to use the [[ -n "$1" ]] method as that would terminate the loop early with an empty string (such as with ./script.sh ab "" c stopping without doing c ).

To iterate over the positional parameters :

for pattern in "$@"; do
  grep -w -- "$pattern" codelist.lst || echo "'$pattern' not Found"
done

For a more advanced usage, which only invokes grep once, use the -f option with a shell process substitution:

grep -w -f <(printf '%s\n' "$@") codelist.lst

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