Pregunta

I have the given text:

# Blub
Hello this is a blub text.

# Bla
This is the bla text.

# Abba
Another text.

Is it possible to sort for the lines with the #? So that the resulting text is:

# Abba
Another text.

# Bla
This the bla text.

# Blub
Hello this is a blub text.

Preferably using vim or emacs.

¿Fue útil?

Solución

In Emacs,

  1. M-xsort-regexp-fields
  2. Enter: #[^#]*
  3. Enter: \&

The first regexp delimits the record, and the second specifies the key for sorting.

If you're at liberty to choose the marker character and use * instead of #, you may use org-mode's command org-sort-entries instead, which saves you from entering the regexps.

Otros consejos

Something like:

:sort! /^#.+\n.+\n$/ 

I'm not sure about line block order.

You didn't tag it as such, but I think awk is the best tool for the job. Using gawk the following works:

gawk RS='\n\n' '{ 
  gsub("\n$", "")
  gsub("\n", "@")
  print 
}' file_to_be_sorted | sort | sed -e 's/$/\n/' -e 's/@/\n/'

Explanation

By setting the record separator (RS) to '\n\n' gawk creates records from each block. Each record is converted to be on one line with @ as separator (gsub("\n", "@")), at this point normal sort works. sed is then used to recreate the blocks. gsub("\n$", "") fixes a whitespace issue with the last record.

Note: if any of the blocks contains @ you need to choose a different separator.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top