【问题标题】:how to merge similar lines in linux如何在linux中合​​并相似的行
【发布时间】:2013-07-27 11:30:21
【问题描述】:

我的 linux 系统上有一个文件 test.txt,其中包含以下格式的数据:

first second third fourth 10  
first second third fourth 20  
fifth sixth seventh eighth 10  
mmm nnn ooo ppp 10  
mmm nnn ooo ppp 20   

我需要修改格式如下 -

first second third fourth 10 20  
fifth sixth seventh eighth 10 0  
mmm nnn ooo ppp 10 20  

我试过下面的代码

cat test.txt | sed 'N;s/\n/ /' | awk -F" " '{if ($1~$5){print $1" "$2" "$3" "$4" "$8} else { print $0 }}'

但这并没有提供所需的输出。当有一行下面没有类似的行时,此命令将失败。你能建议我解决这个问题吗?

【问题讨论】:

    标签: linux shell sed awk merge


    【解决方案1】:

    这是一种方法:

    awk ' {
      last=$NF; $NF=""
      if($0==previous) {
        tail=tail " " last
      }
      else {
        if(previous!="") {
          if(split(tail,foo)==1) tail=tail " 0"
          print previous tail
        }
        previous=$0
        tail=last
      }
    }
    END {
        if(previous!="") print previous tail
    }
    '
    

    【讨论】:

      【解决方案2】:

      Perl 解决方案:

      perl -ne '/^(.*) (\S+)/ and push @{ $h{$1} },$2 }{ print "$_ @{$h{$_}}\n" for keys %h' < test.txt
      

      【讨论】:

        【解决方案3】:

        重用my solution (J4F)

        cat file.txt | sort | while read L;
        do
          y=`echo $L | rev | cut -f2- -d' ' | rev`;
          {
            test "$x" = "$y" && echo -n " `echo $L | awk '{print $NF}'`";
          } || 
          {
            x="$y";echo -en "\n$L"; 
          };
        done
        

        【讨论】:

          猜你喜欢
          • 2012-04-18
          • 2014-10-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-01
          • 2011-09-18
          • 1970-01-01
          相关资源
          最近更新 更多