bash 如何在变量中 grep 复杂的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2106526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:52:15  来源:igfitidea点击:

How can I grep complex strings in variables?

bashvariablesgrepif-statement

提问by Craig

I am trying to grep for a small string in a much larger string. Both strings are being stored as variables and here is a code example:

我试图在一个更大的字符串中搜索一个小字符串。两个字符串都被存储为变量,这里是一个代码示例:

#!/bin/bash

long_str=$(man man)
shrt_str="guide"

if grep -q $shrt_str $long_str ; then
        echo "Found it!"
fi

I don't think variable expansion is working the way I expect it to. I have tried [ ]and [[ ]], also quoting the variables and piping the output to /dev/nullbut no matter what I do it won't work.

我认为变量扩展并没有像我期望的那样工作。我已经尝试过,[ ]并且[[ ]]还引用了变量并将输出管道传输到/dev/null但无论我做什么都行不通。

Does anyone have any ideas?

有没有人有任何想法?

回答by ghostdog74

if echo "$long_str" | grep -q "$shrt_str";then
  echo "found"
fi

or

或者

echo "$long_str" | grep  -q  "$shrt_str"  && echo "found" || echo "not found"

But since you are using bash shell, then use shell internals. No need to call external commands

但是既然您使用的是 bash shell,那么请使用 shell 内部结构。无需调用外部命令

shrt_str="guide"
case "$long_str" in 
   *"$shrt_str"* ) echo "Found";;
   * ) echo "Not found";;
esac

回答by Ignacio Vazquez-Abrams

grep is for files or stdin. If you want to use a variable as stdin then you need to use bash's herestring notation:

grep 用于文件或标准输入。如果你想使用一个变量作为标准输入,那么你需要使用 bash 的 herestring 表示法:

if grep -q "$shrt_str" <<< "$long_str" ; then

回答by Alok Singhal

You want

你要

if echo $long_str | grep -q $shrt_str; then

回答by Paused until further notice.

Another Bash-specific technique:

另一种 Bash 特定的技术:

if [[ $long =~ $short ]]    # regex match
then
    echo "yes"
fi

But if you don't need the long string in a variable:

但是,如果您不需要变量中的长字符串:

if man man | grep $short; then ...

but I'm assuming that was just for the purpose of having an example.

但我假设这只是为了举个例子。