2

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]
....
....

我的脚本会读取文件名 [a] 的 input.conf 并将其放入临时文件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

我想以可变的方式进行操作,因为我可能必须在某些文件中匹配多个模式。

4

1 回答 1

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"
于 2012-08-09T19:57:08.263 回答