当选项作为变量传递时,diff -I(大写'i')不起作用

时间:2012-08-09 18:31:12

标签: shell unix diff gnu

我正在编写一个脚本,使用diff命令的GNU版本找出文件之间的差异。在这里,我需要忽略html注释<! - 以及匹配的任何模式(通过文件提供输入)。

档案wxy/a

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
some text here
           <property name="loginUrl" value="http://localhost:15040/ab/ssoLogin"/>
     <!--property name="cUrl" value="http://localhost:15040/ab/ssoLogin" /-->
</beans>

档案xyz/a

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
some text there
           <property name="loginUrl" value="http://localhost:15045/ab/ssoLogin"/>
     <!--property name="cUrl" value="http://localhost:15045/ab/ssoLogin" /-->
</beans>

模式输入文件:input.conf

[a]
http://.*[:0-9]*/ab/ssoLogin
[some other file]
....
....

我的脚本会读取input.conf中的文件名[a]并放入临时文件lines_to_ignore,现在我读取文件lines_to_ignore并将模式附加到如下变量

compare_file.sh

diff_ignore_options="-I \"\!--\"" # Ignore option for <!-- Comments

for iline in `cat lines_to_ignore`; do
    diff_ignore_options=${diff_ignore_options}" -I \"$iline\""
    echo "-----------------------------------------------------------"
    diff -I "\!--" -I "$iline" wxy/a xyz/a
    echo "-----------------------------------------------------------"
done

diff $diff_ignore_options wxy/a xyz/a 

现在输出:

-----------------------------------------------------------
19c19
< some text here
---
> some text there
-----------------------------------------------------------

19,21c19,21
< some text here
<            <property name="loginUrl" value="http://localhost:15040/ab/ssoLogin"/>
<      <!--property name="cUrl" value="http://localhost:15040/ab/ssoLogin" /-->
---
> some text there
>            <property name="loginUrl" value="http://localhost:15045/ab/ssoLogin"/>
>      <!--property name="cUrl" value="http://localhost:15045/ab/ssoLogin" /-->

为什么diff命令中的变量替换不起作用?

diff $diff_ignore_options wxy/a xyz/a

我想以变量方式实现,因为我可能需要在某些文件中匹配多个模式。

1 个答案:

答案 0 :(得分:3)

问题是!字符,shell用于历史记录扩展。此外,您在$diff_ignore_options变量中包含转义双引号字符;由于您要忽略的模式不包含任何"个字符,因此您不希望这样。

这应该有用(注意使用单引号来避免将!视为元字符):

diff_ignore_options='-I !--'
diff $diff_ignore_options this_file that_file

然后你可以添加更多这样的模式:

diff_ignore_options="$diff_ignore_options -I foobar"