bash 将变量传递给 grep 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19669968/
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-18 08:26:37  来源:igfitidea点击:

Pass variable to grep command

linuxbashgrep

提问by MSK

I want to pass a variable in my grepcommand in Linux bash script. Variable is a text file from Internet and i want to find some words in it.

我想grep在 Linux bash 脚本的命令中传递一个变量。变量是来自 Internet 的文本文件,我想在其中查找一些单词。

I have tried the following command in my bash:

我在我的 bash 中尝试了以下命令:

  1. cat "$var" | grep -Po '(?<=\d[a-zA-Z]).*\..*(?=[a-zA-Z]\d)'
  2. echo "$var" | grep -Po '(?<=\d[a-zA-Z]).*\..*(?=[a-zA-Z]\d)'
  3. grep -Po '(?<=\d[a-zA-Z]).*\..*(?=[a-zA-Z]\d)' <<< "$var"
  1. cat "$var" | grep -Po '(?<=\d[a-zA-Z]).*\..*(?=[a-zA-Z]\d)'
  2. echo "$var" | grep -Po '(?<=\d[a-zA-Z]).*\..*(?=[a-zA-Z]\d)'
  3. grep -Po '(?<=\d[a-zA-Z]).*\..*(?=[a-zA-Z]\d)' <<< "$var"

but i dont get a right Result. How can i do it?

但我没有得到正确的结果。我该怎么做?

Here is my bash:

这是我的 bash:

#!/bin/sh    
urltext=$(curl -s https://example.com)
string=$(grep -Po '(?<=\d[a-zA-Z]).*\..*(?=[a-zA-Z]\d)' "$urltext" | tr '.' '\n' )
cat $string

回答by Idriss Neumann

What's supposed to be contained in the variable ?

变量中应该包含什么?

It's a file ?

是文件吗?

grep <options> <expression> "$var"

It's a string ?

是字符串吗?

echo "$var"|grep <options> <expression>
grep <options> <expression> <(echo "$var")

NB : try -eoption if there are several lines in $var

注意:-e如果 $var 中有几行,请尝试选项