How to sort a range of lines by length in vim with gawk?

609 Views Asked by At

Short question i'm using this regex https://stackoverflow.com/a/11531819/4779063 to sort lines by lenght in vim but i modified it a little bit to make it work with windows and gawk so i end up having something like this:

  vmap <Leader>su ! gawk -f "{ print length(), $0 \| \"sort -n \| cut -d\\  -f2-\"}"<CR>

but everytime i try to use it it says that it could open a .tmp file in my C:\Users\Username\AppData\Local\Temp\VIi33.tmp

any ideas?

2

There are 2 best solutions below

2
Meninx - メネンックス On

If you want you can try to do that by using only vim to sort your file by length:

:g/^/ s/^.*$/\=substitute(submatch(0),submatch(0),strlen(submatch(0)).'# '.submatch(0),'')/ 
:% sort! n
:% s/^\d\+# //
0
James Brown On

This GNU AWK program sorts records or lines (via an array) based on their length and prints them out in sorted order. Could you use that?

function len_comp_func(i1,v1,i2,v2) {   # define length comparison function for for
  return(length(v1)-length(v2))
}
{
  arr[NR]=$0                            # populate array with all the records
}
END {
  PROCINFO["sorted_in"] = "comp_func"   # define order function
  for (i in arr)                        # traverse in length order
    print arr[i]
}

.