bash 由于用空格扩展变量导致的 Grep 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2543309/
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
Grep error due to expanding variables with spaces
提问by nightfire
I have a file called "physics 1b.sh". In bash, if I try
我有一个名为“ physics 1b.sh”的文件。在 bash 中,如果我尝试
x="physics 1b"
grep "string" "$x".sh
grep complains:
grep 抱怨:
grep: physics 1b: No such file or directory.
However, when I do
但是,当我这样做时
grep "string" physics\ 1b.sh
It works fine. So I guess the problem is something to do with the variable not being expanded to include the backslash that grep needs to recognize the space. How do I get this to work?
它工作正常。所以我猜这个问题与变量没有被扩展以包含 grep 需要识别空间的反斜杠有关。我如何让这个工作?
Using bash 3.2, mac os 10.6.
使用 bash 3.2,mac os 10.6。
Edit:
Never mind, the problem was that x was set to " physics 1b", but when I did echo $xto check the contents, bash chopped off the spaces in the front so I couldn't tell that it was different. The first way above actually works.
编辑:
没关系,问题是 x 被设置为" physics 1b",但是当我 echo $x检查内容时,bash 切掉了前面的空格,所以我看不出它有什么不同。上面的第一种方法确实有效。
回答by Marcelo Cantos
Put the entire argument in double-quotes:
将整个论点放在双引号中:
grep "string" "$x.sh"
回答by Vijay
use this in your script.
在您的脚本中使用它。
grep "string" "${x}.sh"
回答by ghostdog74
another way
其它的办法
grep "string" "${x}.sh"

![bash 帮助 grep [[:alpha:]]* -o](/res/img/loading.gif)