Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

4 Answers 4

up vote 4 down vote accepted
 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.

share|improve this answer
    
Thanks. Worked great! –  sudobash Aug 12 at 15:22
    
@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 at 16:32

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

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
share|improve this answer

One more awk approach:

awk -F ':' '!a[$1]++ && NR>1{print ""}1' file
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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