1

I am writing a script in bash for an address book. Everything is working now except that I am unable to separate alphabetical records with a blank line when the alphabet changes. I have a file which after sorting gives with awk, the output as follows:

Anand Anju
Anand Sanjay
Das Ajay
Deshpande Shweta
Kanetkar Ashok
Kanetkar Jyoti
Sabane Dhananjay
Sahani Surinder

I want to generate the output as given below;

Anand Anju
Anand Sanjay

Das Ajay
Deshpande Shweta

Kanetkar Ashok
Kanetkar Jyoti

Sabane Dhananjay
Sahani Surinder

I desire a solution using awk.

1
  • perl -0777pe 's/^(.).*(?:\n\1.*)+(?=\n.)\K/\n/gm' inputf can also help solve the pbm.
    – user218374
    Jun 28, 2017 at 14:57

4 Answers 4

4

Use awk to pick out the first character of the current input line. If it's different from the first character of the previous line, output a blank line. Remember the first character of this line and then output the current line. This way you get a blank line outputted before each line if the first character changes from what it was on the previous line.

$ awk '{ cur = substr($0,1,1) } NR > 1 && cur != prev { print "" } { prev = cur; print }' file
Anand Anju
Anand Sanjay

Das Ajay
Deshpande Shweta

Kanetkar Ashok
Kanetkar Jyoti

Sabane Dhananjay
Sahani Surinder
1
  • Yesss..it worked. Thanks for the explanation too. Jul 5, 2017 at 4:42
1

Another awk solution:

awk 'NR>1 && a && substr($1,1,1)!=a{ print "" }{ a=substr($1,1,1) }1' file

  • substr($1,1,1) - extract the 1st character from the 1st field
1
awk '{A[$1]++;if(A[$1]==1){printf("\n")}}1' FS= file
1
  • Nice one. Not efficient, but compact.
    – Philippos
    Jun 28, 2017 at 14:05
0

We accumulate the next line into the pattern space and compare the first char of the pattern space with the first char of the last line in the pattern space.

When a match, we append one more line into the pattern space. Now in case we hit the eof, we immediately quit (N) command does it, that's why we don't prefix it with a $! to take advantage of this feature.

Else, we place a newline at the end of the block.

GNU sed is assumed.

sed -e '
   :a;N
   /^\(.\).*\n\1[^\n]*$/ba
   h;s/\(.*\n\).*/\1/p
   g;s/.*\(\n\)/\1/;D
' file.txt

Results

Anand Anju
Anand Sanjay

Das Ajay
Deshpande Shweta

Kanetkar Ashok
Kanetkar Jyoti

Sabane Dhananjay
Sahani Surinder

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .