Sort a text file based on names in square brackets

Hi all,

I have a text file similar to this:

[banana]
Text
More text
Etc

[apple]
Stuff
That
Is
Needed

[friend]
Etc
Etc

This contains over 70 entries and each entry has several lines of text below the name in square brackets.

I want to sort the whole file into a new file in alphabetical order based on the word in the square brackets and keep all text below it, up to the next name in square brackets.

So

[apple]
..
..

[banana]
..
..

[friend]
..
..

How can I do this please?

Thanks,

Al.

Welcome to the forum.

Any attempts / ideas / thoughts from your side?

#!/usr/bin/bash                      
while read line                      
do                                   
if [ "${line:0:1}" = "[" ]           
then                                 
        len=${#line}                 
        (( len = $len - 2 ))         
        outfile=${line:1:$len}       
        echo "$line" >$outfile.txt   
else                                 
        echo "$line" >>$outfile.txt  
fi                                   
done <inputfile                      
 cat *.txt >true_outfile

I ran this in an empty directory except for the input file, and the script.
You may find whatever application you are using this in will be simpler if you keep the intermediate files rather than the final file.

-bash-3.2# l                                                        
total 48                                                            
-rwxr-xr-x    1 root     sys        232 Oct 12 19:37 i              
-rw-r--r--    1 root     sys         76 Oct 12 19:03 inputfile      
-rw-r--r--    1 root     sys         76 Oct 12 19:37 true_outfile   
-bash-3.2# ./i                                                      
-bash-3.2# l                                                        
total 96                                                            
-rw-r--r--    1 root     sys         30 Oct 12 19:40 apple.txt      
-rw-r--r--    1 root     sys         29 Oct 12 19:40 banana.txt     
-rw-r--r--    1 root     sys         17 Oct 12 19:40 friend.txt     
-rwxr-xr-x    1 root     sys        232 Oct 12 19:37 i              
-rw-r--r--    1 root     sys         76 Oct 12 19:03 inputfile      
-rw-r--r--    1 root     sys         76 Oct 12 19:40 true_outfile   
-bash-3.2#                                                          

Try also

awk '$NF=$NF OFS' RS= ORS="\n" FS="\n" OFS="\t" file | sort | tr '\t' '\n'
[apple]
Stuff
That
Is
Needed

[banana]
Text
More text
Etc

[friend]
Etc
Etc


Thanks very much guys, I�ll try later and report back.

Cheers,

Al.

It works a treat, thanks guys

Al.