how to merge similar lines in linux

前端 未结 3 1974
逝去的感伤
逝去的感伤 2021-01-25 16:17

I have a file test.txt on my linux system which has data in following format :

first second third fourth 10  
first second third fourth 20  
fifth sixth sevent         


        
相关标签:
3条回答
  • 2021-01-25 16:42

    Here is one way to do it:

    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
    }
    '
    
    0 讨论(0)
  • 2021-01-25 16:52

    Perl solution:

    perl -ne '/^(.*) (\S+)/ and push @{ $h{$1} },$2 }{ print "$_ @{$h{$_}}\n" for keys %h' < test.txt
    
    0 讨论(0)
  • 2021-01-25 16:57

    Reuse of 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
    
    0 讨论(0)
提交回复
热议问题