Bash unixshell脚本if和grep命令

Bash unixshell脚本if和grep命令,bash,shell,unix,Bash,Shell,Unix,目前我正在编写一个代码: 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

目前我正在编写一个代码:

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中的两个参数,并将输出重定向到由用户的第二个参数命名的文件

我似乎无法让代码正常工作,也许你们中的一些人可以帮我检查错误。 谢谢

这极大地改变了语义,但我相信这正是您试图做的。我添加了-以使其稍微健壮,但如果其中任何一个参数包含正则表达式的元字符,这将失败。但你可以试试:

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

哇,太棒了,除了当我输入1个参数使if条件为真时,一切都正常,它没有运行'then',而是运行'else',只输入一个参数不满足if条件。这个参数也必须在test.txt.aah中,好的,我理解。每当我输入1个参数时,是否有任何更改可以满足IF条件?当然。只需删除表达式的后半部分!
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