由于用空格扩展变量导致的 Grep 错误 [英] Grep error due to expanding variables with spaces
问题描述
我有一个名为physics 1b.sh
"的文件.在 bash 中,如果我尝试
I have a file called "physics 1b.sh
". In bash, if I try
x="physics 1b"
grep "string" "$x".sh
grep 抱怨:
grep: physics 1b: No such file or directory.
但是,当我这样做时
grep "string" physics 1b.sh
它工作正常.所以我猜这个问题与变量没有被扩展以包含 grep 需要识别空间的反斜杠有关.我如何让它发挥作用?
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?
使用 bash 3.2,mac os 10.6.
Using bash 3.2, mac os 10.6.
没关系,问题是 x 被设置为 "physics 1b"
,但是当我做 echo $x
检查内容时,bash 砍掉了前面的空格所以我不能说这是不同的.上面的第一种方法确实有效.
Never mind, the problem was that x was set to " physics 1b"
, but when I did echo $x
to 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.
推荐答案
将整个论点放在双引号中:
Put the entire argument in double-quotes:
grep "string" "$x.sh"
这篇关于由于用空格扩展变量导致的 Grep 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!