簡體   English   中英

UNIX Shell腳本if和grep命令

[英]UNIX shell scripting if and grep command

目前我正在編寫代碼:

egrep '("$1"|"$2")' Cities.txt > test.txt
if [ $# -eq 1] && grep -q "$1" test.txt ; then
grep $1 Cities.txt
elif [ $# -eq 2 ] && egrep -q '("$1"|"$2")' test.txt ; then
egrep '("$1"|"$2")' Cities.txt > $2.txt
else $1 not found on Cities.txt
fi
exit

基本上,它允許用戶輸入1或2個參數,並且該參數在Cities.txt中用作grep模式,並將輸出重定向到名為test.txt的文件

如果用戶輸入了1個參數,並且該參數與test.txt的內容匹配,則它將在文件Cities.txt中顯示包含參數1的行。

如果用戶輸入了2個參數,並且兩個參數都與文件test.txt的內容匹配,則它與Cities.txt中的兩個參數都匹配,並將輸出重定向到用戶的第二個參數命名的文件。

我似乎無法使代碼正常工作,也許有些人可以幫助我檢查錯誤。 謝謝

egrep "($1|$2)" Cities.txt > test.txt    # change single quote to double quote

if [ $# -eq 1 ] && grep -q -- "$1" test.txt ; then
  grep -- "$1" Cities.txt
elif [ $# -eq 2 ] && egrep -q -- "($1|$2)" test.txt ; then
  egrep -- "($1|$2)" Cities.txt > $2.txt
else 
  $1 not found on Cities.txt
fi

這極大地改變了語義,但是我相信您正在嘗試做。 我添加了--試圖使它稍微健壯,但是,如果其中一個參數包含正則表達式的元字符,則此操作將失敗。 但是您可以嘗試:

if test $# -eq 1 && grep -F -q -e "$1" test.txt ; then
    grep -F -e "$1" Cities.txt
elif [ $# -eq 2 ] && grep -q -F -e "$1" -e "$2" test.txt; then
    grep -F -e "$1" -e "$2" Cities.txt > $2.txt
else 
    $1 not found on Cities.txt >&2
fi

暫無
暫無

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

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