如何在不同ip组的行之间添加空行

时间:2014-06-01 23:57:36

标签: text awk

我有一个表格(ip,info)的文件localhost.txt:

192.168.1.8 host name alex
192.168.1.8 macaddress 1354321313
192.168.1.8 time 04:18
192.168.1.20 date 6/2/2012
192.168.1.20 host name riko
192.168.1.11 year 2014
192.168.1.11 host name cr7
192.168.1.11 shared files off
192.168.1.11 time 12:84

我希望输出结果为:

192.168.1.8 host name alex
192.168.1.8 macaddress 1354321313
192.168.1.8 time 04:18

192.168.1.20 date 6/2/2012
192.168.1.20 host name riko

192.168.1.11 year 2014
192.168.1.11 host name cr7
192.168.1.11 shared files off
192.168.1.11 time 12:84

我试过这个

awk '{if(NR > 1 && $2 != prev_two){printf "\n";} prev_two=$2; print $0}' localhost.txt >> result.txt

和这个

awk 'prev != $2 {print ""} {print; prev=$2}' localhost.txt >> result.txt

但非常有效

我读过这个

Add blank line between lines from different groups

3 个答案:

答案 0 :(得分:1)

此:

$ awk '{if(NR > 1 && $1 != prev_two){printf "\n";} prev_two=$1; print $0}' localhost.txt >> result.txt
$ cat result.txt
192.168.1.8 host name alex
192.168.1.8 macaddress 1354321313
192.168.1.8 time 04:18

192.168.1.20 date 6/2/2012
192.168.1.20 host name riko

192.168.1.11 year 2014
192.168.1.11 host name cr7
192.168.1.11 shared files off
192.168.1.11 time 12:84

应该有效。这是您想要分组的第一个字段,而不是第二个字段(因此是$1)。

答案 1 :(得分:1)

您可以使用awk

执行此操作
awk '$1!=a && NR>1 {$0=RS$0} {a=$1} 1' file
192.168.1.8 host name alex
192.168.1.8 macaddress 1354321313
192.168.1.8 time 04:18

192.168.1.20 date 6/2/2012
192.168.1.20 host name riko

192.168.1.11 year 2014
192.168.1.11 host name cr7
192.168.1.11 shared files off
192.168.1.11 time 12:84

答案 2 :(得分:-1)

这不是使用awk的单行,但它有效。

#!/bin/bash

prev=""
while read -r line
do
   cur=$(echo "$line" | awk '{print $1}')
   if [[ "$prev" == "" ]]; then
     prev="$cur"
   elif [[ "$prev" != "$cur" ]]; then
     echo ""
   fi
   echo "$line"
   prev="$cur"
done