我想比较2个文件,例如file1
和file2
,在输出中我必须打印差异以及添加和/或删除的行数。
apple1
apple2
apple3
apple4
apple1
apple2
apple3
apple4
grape1
grape2
grape3
mango4
No of newly added list= 4
No of lines removed =0
Difference =4
Newely Added list
------------
grape1
grape2
grape3
mango4
Removed list
--------
None
如果您不需要该确切的输出格式,则可以使用diff
和diffstat
。
例如
$ diff file1 file2 | diffstat -s
1 file changed, 4 insertions(+)
例如,如果apple4
从中删除了file2
,则输出将如下所示:
$ diff file1 file2 | diffstat -s
1 file changed, 4 insertions(+), 1 deletion(-)
如果确实需要该确切输出,则可以diff
在以下脚本中单独使用:
#! /bin/sh
if [ ! "$#" -eq 2 ] ; then
echo "Exactly two file arguments are required."
exit 1
fi
f1="$1"
f2="$2"
# sort and uniq the input files before diffing.
# if you have `mktemp`, use this:
t1=$(mktemp)
t2=$(mktemp)
# else kludge it with something like this:
# mkdir ~/tmp
# t1="~/tmp/$f1.tmp"
# t2="~/tmp/$f2.tmp"
# if your `sort` has a `-u` option for `uniq` (e.g. GNU sort), you
# can use `sort -u` instead of `sort | uniq`
sort "$f1" | uniq > "$t1"
sort "$f2" | uniq > "$t2"
add=$(diff "$t1" "$t2" | grep -c '^> ')
del=$(diff "$t1" "$t2" | grep -c '^< ')
[ -z "$add" ] && add=0
[ -z "$del" ] && del=0
diff=$(( add - del ))
cat <<__EOF__
No of newly added list= $add
No of lines removed = $del
Difference = $diff
Newly Added list
------------
__EOF__
if [ "$add" -eq 0 ] ; then
echo None.
else
diff "$t1" "$t2" | sed -n -e 's/^> //p'
fi
cat <<__EOF__
Removed list
--------
__EOF__
if [ "$del" -eq 0 ] ; then
echo None.
else
diff "$t1" "$t2" | sed -n -e 's/^< //p'
fi
rm -f "$t1" "$t2"
如果您grep
没有-c
选择,请使用diff ... | grep ... | wc -l
如果您没有内置的整数运算,则可以使用bc
或dc
或其他方式进行计算sh
。我想不起来没有,但商业Unix可以具有一些通用工具的真正原始和古老的实现。该脚本已经过测试,dash
因此可以与任何当前的POSIX shell一起使用。
输出:
$ ./keerthana.sh file1 file2
No of newly added list = 4
No of lines removed = 0
Difference = 4
Newly Added list
------------
grape1
grape2
grape3
mango4
Removed list
--------
None.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句