我怎样才能让 diff 仅显示添加和删除的行

我怎样才能让 diff 仅显示添加和删除的行

如何让 unix 命令 diff 仅显示已添加和已删除的行?如果 diff 无法做到这一点,那么什么工具可以做到?

答案1

我不确定这是否可行,因为很难区分更改、添加和删除的行。

考虑这个文件:

start
old
old
old
end

我们对其进行编辑,使其看起来像这样:

start
old
old but now new
new
new
end

如果我们diff得到这个输出:

< old
< old
---
> old but now new
> new
> new

这很容易生成。但是如果你要求diff只打印添加和删除的行,我认为哪些行被添加和删除以及哪些行被更改就成了见仁见智的问题。例如,我是否删除了最后一行,old并用一行替换它new,或者我是否编辑了它?

答案2

diff -u0你想做的事吗?

答案3

我也有同样的问题。这个函数是我获取最大更改行号(即更改以字母“+”开头)的解决方案。之后,我再次逐行循环遍历 diff 文件,直到触发行进行处理时才发送到行处理器:


#====================================================================
proc_diff_file()    # processes a diff file
#====================================================================
# Arg_1 = Diff File Name
# Arg_2 = New File Name - the one with the new lines
{
  NEW_FILE=$1
  A_FILE=$2
  if [ -f "$A_FILE" ]; then
    echo "processing diff $A_FILE"
    pre_process_diff $A_FILE
    # Set loop separator to end of line
    ndx=0
    BAKIFS=$IFS
    IFS=$(echo -en "\n\b")
    exec 3<&0
    exec 0<$A_FILE
    while read line
    do
      ndx=$(expr $ndx + 1)
      # use $line variable to process line in processLine() function
      if [ $ndx > $max_ndx ]; then
        proc_age $line
      fi
    done
    exec 0<&3
    # restore $IFS which was used to determine what the field separators are
    IFS=$BAKIFS

#    cleanup $NEW_FILE

    echo "processing diff $A_FILE done"
  fi
}

该函数如下:


#====================================================================
pre_process_diff()  # pre-processes a diff file for last changed line
                    # sets a variable named $max_ndx
#====================================================================
# Arg_1 = Diff File Name
{
  A_FILE=$1
  max_ndx=
  # collect last line number of diff + 
  # all lines following are new data
  `grep -n "^[+]" $A_FILE | gawk '-F:' '{ print $1 }' >tmp`
  # Set loop separator to end of line
  # read through to the last line number
  BAKIFS=$IFS
  IFS=$(echo -en "\n\b")
  exec 3<&0
  exec 0<tmp
  while read last_line
  do
    max_ndx=$last_line
  done
  exec 0<&3
  # restore $IFS which was used to determine what the field separators are
  IFS=$BAKIFS
  echo "pre-processing diff $A_FILE done max_ndx=$max_ndx"
}

史蒂夫

答案4

我觉得最简单使用 grep

添加的行:

grep -xvFf filea.txt fileb.txt

删除的行:

grep -xvFf fileb.txt filea.txt

-x:匹配整行
-v:与模式不匹配的行
-F:将模式视为固定字符串,而不是正则表达式
-f <otherfile>:从文件中读取模式列表

相关内容