简体   繁体   中英

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM