shell - 如何逐字比较2个文件并将不同的单词存储在结果输出文件中
问题描述
假设有两个文件:
文件1.txt
My name is Anamika.
文件2.txt
My name is Anamitra.
我想要结果文件存储:
结果.txt
Anamika
Anamitra
我使用腻子,所以不能使用 wdiff,任何其他选择。
解决方案
不是我最好的剧本,但它有效。其他人可能会想出更优雅的东西。
#!/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
命令只保留字母数字字符。
推荐阅读
- java - 类型不匹配:无法将 session.setPortForwardingL() 从 void 转换为 int;
- javascript - 如何在 NetSuite 上的 beforeLoad 功能中操作记录?
- php - 从 PHP 中的结果准备 json 数组
- ios - 如何在终端上从 xcarchive 导出 dsym 文件
- reactjs - 嵌套路由器不工作代码拆分
- javascript - 如何将 id 名称传递给 jQuery 验证并发送到控制器?
- angular - 角度 6 中的多项目旋转木马
- android - 使用 alt beacon libaray 从最近的应用程序关闭应用程序时,信标不扫描
- angular - 在 Angular 6+ 应用程序中使用带有 observables 的 Reselect
- ubuntu-18.04 - CoTurn 服务器在 600 秒后停止媒体