我在我的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 }}'
但是这不是要求的输出。 当有一条线在它下面没有相似的线时,这个命令失败。 你可以build议我任何解决scheme?
这是一个办法:
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 } '
Perl解决方案:
perl -ne '/^(.*) (\S+)/ and push @{ $h{$1} },$2 }{ print "$_ @{$h{$_}}\n" for keys %h' < test.txt
重用我的解决方案 (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