簡體   English   中英

bash/ksh grep 腳本接受多個參數

[英]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

這是我的腳本,它現在完全按照我想要的方式工作,如果我添加更多,我想添加 arguments 它會給我多個輸出,我該怎么做?

所以例如我做./test.sh apple 它會在 codelist.lst 中顯示 grep apple 並給我 output: Apple

我想做./test.sh apple orange 並且會做:Apple Orange

您可以使用shift和循環來做到這一點,例如(適用於bashksh ):

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

您會注意到我還選擇使用[[ -n "$1" ]]方法,因為這會提前終止循環並返回一個空字符串(例如./script.sh ab "" c停止c )。

遍歷位置參數

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

對於更高級的用法,它只調用 grep 一次,請使用-f選項和 shell 進程替換:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM