diff
是否可以使用(或另一个简单的 bash 命令)检查两个文件的第一行是否相等?
[通常检查第一行/最后一行的相等性k
,甚至是 i 到 j 行]
区分两个文件的前 k 行:
$ diff <(head -k file1) <(head -k file2)
同样,要区分最后 k 行:
$ diff <(tail -k file1) <(tail -k file2)
区分线 i 到 j:
diff <(sed -n 'i,jp' file1) <(sed -n 'i,jp' file2)
与上面的 dogbane 相比,我的解决方案似乎相当基本和初学者,但在这里都是一样的!
echo "Comparing the first line from file $1 and $2 to see if they are the same."
FILE1=`head -n 1 $1`
FILE2=`head -n 1 $2`
echo $FILE1 > tempfile1.txt
echo $FILE2 > tempfile2.txt
if diff "tempfile1.txt" "tempfile2.txt"; then
echo Success
else
echo Fail
fi
我的解决方案使用patchutils程序集合的filterdiff程序。以下命令显示了 file1 和 file2 从行号 j 到 k 之间的区别:
diff -U 0 file1 file2 | filterdiff --lines j-k
下面的命令显示两个文件的第一行。
krithika.450> head -1 temp1.txt temp4.txt
==> temp1.txt <==
Starting CXC <...> R5x BCMBIN (c) AB 2012
==> temp4.txt <==
Starting CXC <...> R5x BCMBIN (c) AB 2012
如果两个文件中的第一行相等,则下面的命令显示 yes。
krithika.451> head -1 temp4.txt temp1.txt | awk '{if(NR==2)p=$0;if(NR==5){q=$0;if(p==q)print "yes"}}'
yes
krithika.452>