由于用空格扩展变量而导致的 Grep 错误

发布于 2024-08-27 13:27:15 字数 515 浏览 3 评论 0原文

我有一个名为“physical 1b.sh”的文件。在 bash 中,如果我尝试

x="physics 1b"
grep "string" "$x".sh

grep 会抱怨:

grep:  physics 1b: No such file or directory.

但是,当我这样做时

grep "string" physics\ 1b.sh 

它工作得很好。所以我想问题是与变量没有被扩展以包含 grep 需要识别空格的反斜杠有关。我该如何让它发挥作用?

使用bash 3.2,mac os 10.6。

编辑:
没关系,问题是 x 被设置为 "physical 1b",但是当我执行 echo $x 检查内容时,bash 砍掉了前面的空格所以我看不出它有什么不同。上面的第一种方法确实有效。

I have a file called "physics 1b.sh". In bash, if I try

x="physics 1b"
grep "string" "$x".sh

grep complains:

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?

Using 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 $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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

生生漫 2024-09-03 13:27:15

将整个参数放在双引号中:

grep "string" "$x.sh"

Put the entire argument in double-quotes:

grep "string" "$x.sh"
々眼睛长脚气 2024-09-03 13:27:15

在你的脚本中使用它。

grep "string" "${x}.sh"

use this in your script.

grep "string" "${x}.sh"
微凉徒眸意 2024-09-03 13:27:15

另一种方式

grep "string" "${x}.sh"

another way

grep "string" "${x}.sh"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文