如果当前行和最后一行的第一列不同,则打印该行

时间:2018-11-06 21:10:58

标签: awk

我需要打印第一列的值与最后一行的第一列的值不同的行。

示例:

1 one                    line number1
1 one one one            line number2
2 two two                line number3
2 two two two            line number4
2 two two two            line number5
2 two two two two        line number6
2 two two two two two    line number7
3 three                  line number8
3 three three            line number9
4 four                   line number10
5 five                   line number11
5 five five five         line number12
5 five five              line number13
6 six                    line number14
6 six six                line number15
6 six                    line number16
6 six                    line number17

我需要以下结果,因为这表示与第一行的最后一行相比,第一列具有不同的行。

1 one one one            line number2
2 two two                line number3
2 two two two two two    line number7
3 three                  line number8
3 three three            line number9
4 four                   line number10
5 five                   line number11
5 five five              line number13
6 six                    line number14

我尝试了以下命令,但没有帮助。

echo "$x" |awk '{t=$1;line=$0;next} $1!=t{print line ORS $0}'

1 个答案:

答案 0 :(得分:1)

类似的事情会起作用,但是我发现您的逻辑很难遵循...

$ awk 'p && p!=$1 {if(!a[NR-1]) print prev; print; a[NR]++} 
                  {p=$1; prev=$0}' file

1 one one one            line number2
2 two two                line number3
2 two two two two two    line number7
3 three                  line number8
3 three three            line number9
4 four                   line number10
5 five                   line number11
5 five five              line number13
6 six                    line number14