简体   繁体   English

shell脚本grep命令

[英]shell scripting grep command

I want to find whether a string contains a forward slash using "grep" command. 我想使用“grep”命令查找字符串是否包含正斜杠。 It is easy at the beginning, and I wrote the following script. 一开始很容易,我写了下面的脚本。

foo=someone/books
if [ `echo "$foo" | grep '/'` ]
then
    echo "has forward slash"
fi

however, the problem is in the corner, if I set the variable "foo" to the following string, 但问题是在角落,如果我将变量“foo”设置为以下字符串,

foo="someone/books in stack"

The above script will be failed since there is "space" in variable foo, when the command expands, the condition in if statement is as below. 由于变量foo中存在“space”,因此上述脚本将失败,当命令扩展时,if语句中的条件如下所示。

grep '/' someone/books in stack

Because of "space", the above "grep" command has too many arguments that is illegal. 由于“空间”,上面的“grep”命令有太多的参数是非法的。 FYI, I try to solved this problem using case statement: 仅供参考,我尝试使用案例陈述来解决这个问题:

case $foo in
    */*)
        echo "has forward slash"
        ;;
    *)
        ;;
esac

However, I do not want to use case statement since it's verbose. 但是,我不想使用case语句,因为它很冗长。 So how could I solved this problem using grep command or others? 那么如何使用grep命令或其他方法解决这个问题呢?

You are not using the if-statement correctly. 您没有正确使用if语句。 The command in the if-condition needs to be quoted so that it becomes a single string when expanded. 需要引用if条件中的命令,以便在展开时它成为单个字符串。 Like this: 像这样:

if [ "`echo "$foo" | grep '/'`" ]
then
    echo "has forward slash"
fi

Or even better is if you check the return code of grep in your if-condition: 或者更好的是,如果你在if条件中检查grep的返回码:

if $(echo "$foo" | grep -q '/')
then
    echo "has forward slash"
fi

You can also do away with the grep and use this instead: 您也可以取消grep并使用它:

foo="someone/books in stack"
if [[ "$foo" == */* ]]
then
  echo "has forward slash"
fi
foo="someone/books with spaces"
bar=`echo $foo | grep '/'`
if [ $? -eq 0 ]
then
    echo "$foo has forward slash"
fi

This works for me. 这适合我。

If you don't want to resort to using exit status this way, I suggest you take a look at dogbane's reply for a more correct answer. 如果您不想以这种方式使用退出状态,我建议您查看dogbane的回复以获得更正确的答案。

There's nothing wrong with being verbose -- it often aids maintainability. 冗长并没有错 - 它通常有助于可维护性。 However, you can terse it up: You don't need every newline, nor do you need the default branch if you do nothing in it. 但是,您可以将其简化:您不需要每个换行符,如果您不执行任何操作,也不需要默认分支。

case "$foo" in
    */*) echo "has forward slash" ;;
esac

If you insist on using grep, use the return status from it and not the output: 如果你坚持使用grep,请使用它的返回状态而不是输出:

if echo "$foo" | grep -q /; then
    echo "has forward slash"
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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