Sort text blocks

I recently came across a simple task, wherein i had to sort a massive text file which was an output of a heavy data crunching code.
In pursuit of the short and easy way to do a block sort on each text blocks separated by a new line character, the first think that appeared to me for solving this was indeed BASH.

The output of the program was something like:

# Block-1
....
....
 
# Block-2 
....
....
 
# Block-N
....
....
<code>
Had to sort each block, the advantage was that it was separated by a new line. The below is what i did in BASH and awk to solve the problem.
 
<b>BASH version:</b>
<pre style='color:#000000;background:#ffffff;'>buffer=; 
{ <span style='color:#7f0055; font-weight:bold; '>while</span> <span style='color:#7f0055; font-weight:bold; '>read</span> -r; 
<span style='color:#7f0055; font-weight:bold; '>do</span> <span style='color:#7f0055; font-weight:bold; '>if</span> <span style='color:#2a00ff; '>[</span><span style='color:#2a00ff; '>[ $REPLY </span><span style='color:#2a00ff; '>]</span>]; <span style='color:#7f0055; font-weight:bold; '>then</span>
      buffer+=<span style='color:#2a00ff; '>"</span><span style='color:#2a00ff; '>$REPLY</span><span style='color:#2a00ff; '>"</span>$<span style='color:#2a00ff; '>'\n'</span>; 
   <span style='color:#7f0055; font-weight:bold; '>else</span> 
      sort &lt;&lt;&lt;<span style='color:#2a00ff; '>"</span><span style='color:#2a00ff; '>$buffer</span><span style='color:#2a00ff; '>"</span>; 
      buffer=; 
   <span style='color:#7f0055; font-weight:bold; '>fi</span>; 
<span style='color:#7f0055; font-weight:bold; '>done</span>; sort &lt;&lt;&lt;<span style='color:#2a00ff; '>"</span><span style='color:#2a00ff; '>$buffer</span><span style='color:#2a00ff; '>"</span>; } &lt; unsorted > sorted
</pre>
 
The code is a simple play and sheer power of bash redirections.
The <i>read -r</i> does not allow backslashes to escape any characters.

Share this