简体   繁体   English

UNIX Shell脚本if和grep命令

[英]UNIX shell scripting if and grep command

currently I'm working on a code : 目前我正在编写代码:

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

basically, it lets user to enter 1 or 2 arguments and the argument(s) is/are used as a grep pattern in Cities.txt and redirect the output to a file named test.txt 基本上,它允许用户输入1或2个参数,并且该参数在Cities.txt中用作grep模式,并将输出重定向到名为test.txt的文件

If the user entered 1 argument and the argument matched the content of the test.txt , then it display the lines that contain argument 1 on file Cities.txt. 如果用户输入了1个参数,并且该参数与test.txt的内容匹配,则它将在文件Cities.txt中显示包含参数1的行。

If the user entered 2 argument and both argument matched the content of the file test.txt, then it matched both argument in Cities.txt and redirect the output to the file named by the user's second argument. 如果用户输入了2个参数,并且两个参数都与文件test.txt的内容匹配,则它与Cities.txt中的两个参数都匹配,并将输出重定向到用户的第二个参数命名的文件。

I couldn't seem to get the code to work, may be some of you guys could help me inspect the error. 我似乎无法使代码正常工作,也许有些人可以帮助我检查错误。 thanks 谢谢

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

This greatly changes the semantics, but I believe is what you are trying to do. 这极大地改变了语义,但是我相信您正在尝试做。 I've added -- to try to make this slightly robust, but if either argument contains metacharacters for the regex this will fail. 我添加了--试图使它稍微健壮,但是,如果其中一个参数包含正则表达式的元字符,则此操作将失败。 But you could try: 但是您可以尝试:

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