san*_*ddy 11 bash file-comparison
如何在shell脚本中找到匹配数据的两个文件并在shell中的另一个文件中重复存储数据?
#!/bin/bash
file1="/home/vekomy/santhosh/bigfiles.txt"
file2="/home/vekomy/santhosh/bigfile2.txt"
while read -r $file1; do
while read -r $file2 ;do
if [$file1==$file2] ; then
echo "two files are same"
else
echo "two files content different"
fi
done
done
Run Code Online (Sandbox Code Playgroud)
我写了代码,但没有用。怎么写?
Kus*_*nda 27
要测试两个文件是否相同,请使用cmp -s
:
#!/bin/bash
file1="/home/vekomy/santhosh/bigfiles.txt"
file2="/home/vekomy/santhosh/bigfile2.txt"
if cmp -s "$file1" "$file2"; then
printf 'The file "%s" is the same as "%s"\n' "$file1" "$file2"
else
printf 'The file "%s" is different from "%s"\n' "$file1" "$file2"
fi
Run Code Online (Sandbox Code Playgroud)
该-s
标志cmp
将公用事业“沉默”。cmp
比较两个相同的文件时,的退出状态将为零。这在上面的代码中用于打印关于两个文件是否相同的消息。
如果您的两个输入文件包含要比较的文件的路径名列表,则使用双循环,如下所示:
#!/bin/bash
file1="/home/vekomy/santhosh/bigfiles.txt"
file2="/home/vekomy/santhosh/bigfile2.txt"
if cmp -s "$file1" "$file2"; then
printf 'The file "%s" is the same as "%s"\n' "$file1" "$file2"
else
printf 'The file "%s" is different from "%s"\n' "$file1" "$file2"
fi
Run Code Online (Sandbox Code Playgroud)
在这里,结果在终端和文件中产生file-comparison.out
。
假设两个输入文件中的路径名都不包含任何嵌入的换行符。
代码首先files1
使用mapfile
. 我这样做是为了避免多次读取该文件,因为我们必须为另一个文件中的每个路径名遍历所有这些路径名。您会注意到$filelist1
,我只是遍历files1
数组中的名称,而不是从内部循环中读取。
最简单的方法是使用命令diff
。
例子:
让我们假设第一个文件是file1.txt
,他包含:
I need to buy apples.
I need to run the laundry.
I need to wash the dog.
I need to get the car detailed.`
Run Code Online (Sandbox Code Playgroud)
和第二个文件 file2.txt
I need to buy apples.
I need to do the laundry.
I need to wash the car.
I need to get the dog detailed.
Run Code Online (Sandbox Code Playgroud)
然后我们可以使用 diff 自动为我们显示使用以下命令在两个文件之间哪些行不同:
diff file1.txt file2.txt
输出将是:
2,4c2,4
< I need to run the laundry.
< I need to wash the dog.
< I need to get the car detailed.
---
> I need to do the laundry
> I need to wash the car.
> I need to get the dog detailed.
Run Code Online (Sandbox Code Playgroud)
我们来看看这个输出是什么意思。要记住的重要一点是,当 diff 向您描述这些差异时,它是在规定的上下文中进行的:它告诉您如何更改第一个文件以使其与第二个文件匹配。差异输出的第一行将包含:
在上面的输出中,“2,4c2,4”表示:“第一个文件中的第2行到第4行需要更改以匹配第二个文件中的第2行到第4行。” 然后它告诉我们每个文件中这些行的内容: