2

I have following output from script

host1:101
host1:102
host2:101
host2:102
host2:103
host4:101
host5:101
host5:102
host5:103
host5:104

etc..

I wanted to insert a new line after each host group.

host1:101
host1:102

host2:101
host2:102

host3:101
host3:102

Any AWK onliners to compare each consecute line with 1st field and insert new line before non-matching 1st field?

4 Answers 4

4
 awk -F: '{if (NR>1 && save!=$1) print "";} {save=$1; print;}'

You never want to insert a blank line before line 1, so don't even think about it unless NR>1.  Thereafter, print the blank line if the first field is not the saved value from the previous line.

1
  • @sudobash: If you believe that this is the best answer (or the clearest, best-explained answer, or the first posted among comparably good answers), you can "accept" it by clicking on the green check mark to the left. Commented Aug 12, 2014 at 16:32
2

Another awk:

awk -F: 'a!~$1{print x}a=$1' file

Remove first blank line of output

awk -F: 'a&&a!~$1{print x}a=$1' file
2
  • 1
    +1: Though better to add awk -F: 'a!~$1 && NR>1{print x}a=$1' file to prevent the empty first line. Commented Aug 13, 2014 at 1:14
  • @jaypal in hindsight could also have done awk -F: 'a&&a!~$1{print x}a=$1' file Commented Aug 13, 2014 at 10:57
1

One more awk approach:

awk -F ':' '!a[$1]++ && NR>1{print ""}1' file
0
1

Another awk:

$ awk -F':' 'FNR > 1 && p != $1 {printf "\n"};{p = $1}1' file
host1:101
host1:102

host2:101
host2:102
host2:103

host4:101

host5:101
host5:102
host5:103
host5:104

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.