繁体   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