首页 > 解决方案 > 如何逐字比较2个文件并将不同的单词存储在结果输出文件中

问题描述

假设有两个文件:

文件1.txt

My name is Anamika.

文件2.txt

My name is Anamitra.

我想要结果文件存储:

结果.txt

Anamika                
Anamitra 

我使用腻子,所以不能使用 wdiff,任何其他选择。

标签: shellunix

解决方案


不是我最好的剧本,但它有效。其他人可能会想出更优雅的东西。

#!/bin/bash

if [ $# != 2 ]
then
    echo "Arguments: file1 file2"
    exit 1
fi

file1=$1
file2=$2

# Do this for both files
for F in $file1 $file2
do
    if [ ! -f $F ]
    then
        echo "ERROR: $F does not exist."
        exit 2
    else
        # Create a temporary file with every word from the file
        for w in $(cat $F)
        do
            echo $w >> ${F}.tmp
        done
    fi
done

# Compare the temporary files, since they are now 1 word per line
# The egrep keeps only the lines diff starts with > or <
# The awk keeps only the word (i.e. removes < or >)
# The sed removes any character that is not alphanumeric.
#         Removes a . at the end for example
diff ${file1}.tmp ${file2}.tmp | egrep -E "<|>" | awk '{print $2}' | sed 's/[^a-zA-Z0-9]//g' > Result.txt

# Cleanup!
rm -f ${file1}.tmp ${file2}.tmp

这使用了for循环的技巧。如果您for在文件上使用 a to 循环,它将在每个单词上循环。并非像 bash 初学者那样的每一行都倾向于相信。这实际上是一件好事,因为它将文件转换为每行 1 个单词。

例如:文件内容==循环完成后,临时文件将包含This is a sentence.
for

This
is
a
sentence.

diff然后在文件上运行是微不足道的。最后一个细节,您的示例输出最后没有包含 a .,因此sed命令只保留字母数字字符。


推荐阅读