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
 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.

  • @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. – G-Man Aug 12 '14 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
  • 1
    +1: Though better to add awk -F: 'a!~$1 && NR>1{print x}a=$1' file to prevent the empty first line. – jaypal singh Aug 13 '14 at 1:14
  • @jaypal in hindsight could also have done awk -F: 'a&&a!~$1{print x}a=$1' file – user78605 Aug 13 '14 at 10:57
1

One more awk approach:

awk -F ':' '!a[$1]++ && NR>1{print ""}1' file
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.