本文介绍了由于使用空格扩展变量,导致Grep错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"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错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:39