BASH:可以在命令行上 grep,但不能在脚本中

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

BASH: can grep on command line, but not in script

linuxbashgrep

提问by Crazy_Bash

Did this million times already, but this time it's not working I try to grep "$TITLE" from a file. on command line it's working, "$TITLE" variable is not empty, but when i run the script it finds nothing

已经做了一百万次,但这次它不起作用我尝试从文件中 grep "$TITLE"。在命令行上它正在工作,“$TITLE”变量不为空,但是当我运行脚本时它什么也没找到

*title contains more than one word

*标题包含多于一个词

echo "$TITLE"
cat PAGE.$TEMP.2 | grep "$TITLE"

what i've tried:

我试过的:

echo "cat PAGE.$TEMP.2 | grep $TITLE"

to see if title is not empty and file name is actually there

查看标题是否为空,文件名是否实际存在

回答by cdarke

Are you sure that $TITLEdoes not have leading or trailing whitespace which is not in the file? Your fix with the string would strip out whitespace before execution, so it would not see it.

您确定$TITLE没有文件中没有的前导或尾随空格吗?您对字符串的修复会在执行之前去除空格,因此它不会看到它。

For example, with a file containing 'Line one':

例如,对于包含“第一行”的文件:

/home/user1> TITLE=' one '
/home/user1> grep "$TITLE" text.txt
/home/user1> cat text.txt | grep $TITLE
Line one

Try echo "<$TITLE>", or echo "$TITLE"|od -xcwhich sould enable you to spot errant chars.

Try echo "<$TITLE>",或者echo "$TITLE"|od -xc哪个可以让您发现错误的字符。

回答by chepner

This command

这个命令

echo "cat PAGE.$TEMP.2 | grep $TITLE"

echoes a string that starts with 'cat'. It does not run a command. You would want

回显以“cat”开头的字符串。它不运行命令。你会想要

echo "$( cat PAGE.$TEMP.2 | grep $TITLE )"

although that is identical in functionality to the simpler

虽然这与更简单的功能相同

cat PAGE.$TEMP.2 | grep $TITLE

And as pointed out by others, there is no need to pipe a single file using cat; grepcan read from files just fine:

正如其他人所指出的,没有必要使用管道管理单个文件catgrep可以从文件中读取就好了:

grep "$TITLE" "PAGE.$TEMP.2"

(Your default behavior should be to quote parameter expansions, unless you can show it is incorrect to do so.)

(你的默认行为应该是引用参数扩展,除非你能证明这样做是不正确的。)

回答by ?imon Tóth

Works for me:

对我有用:

~> cat test.dat
abc
cda
xyz
~> export GRP=cda
~> cat test.dat | grep $GRP
cda

Edit:

编辑:

Also the proper way to use grepis:

另外正确的使用方法grep是:

~> grep $GRP test.dat