[英]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?这是我的脚本,它现在完全按照我想要的方式工作,如果我添加更多,我想添加 arguments 它会给我多个输出,我该怎么做?
So For Example I do./test.sh apple it will grep apple in codelist.lst and Give me the output: Apple所以例如我做./test.sh apple 它会在 codelist.lst 中显示 grep apple 并给我 output: Apple
I want to do./test.sh apple orange and will do: Apple Orange我想做./test.sh apple orange 并且会做:Apple Orange
You can do that with shift
and a loop, something like (works in both bash
and ksh
):您可以使用
shift
和循环来做到这一点,例如(适用于bash
和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
).您会注意到我还选择不使用
[[ -n "$1" ]]
方法,因为这会提前终止循环并返回一个空字符串(例如./script.sh ab "" c
停止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 一次,请使用
-f
选项和 shell 进程替换:
grep -w -f <(printf '%s\n' "$@") codelist.lst
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.