Sort lines in text file between patterns

You can do this with GNU awk in the following way:

$ awk 'BEGIN{PROCINFO["sorted_in"]="@val_num_asc"; FS=","}
       /PATTERN/{
         for(i in a) print i
         delete a
         print; next
       }
       { a[$0]=$2 }
       END{ for(i in a) print i }' file

With PROCINFO["sorted_in"]="@val_num_asc", we tell GNU awk to traverse the arrays in a way that the values of the array elements appear in numerical ascending order. The idea is to make an array with key the full line and value the second field. We don't use the second field as key as there might be duplicates. This could still be achieved however in the following way:

$ awk 'BEGIN{PROCINFO["sorted_in"]="@val_num_asc"; FS=","}
       /PATTERN/{
         for(i in a) print a[i]
         delete a
         print; next
       }
       ($2 in a){ a[$2]=a[$2] ORS $0; next }
       { a[$2] = $0 }
       END{ for(i in a) print a[i] }' file

Tags:

Python

Awk

Sed