I have file with line format as follows:

<something> <file_name> type:file <something> size:<filesize> <something>

I would like to sort numerically it by the field "filesize" identified by label "size:". The simple key number/offset passed usually to sort program doesn't work because there is no strict separator - multiple spaces can occur before "size:" label - for example in "file_name". Is there any way to sort from command line using preceding label as a field identifier?


If no colon in <something>'s, you could say:

sort -t : -Vk 3 file
  • Great, it works. I thought it'll try to parse 'filesize' field till the next colon but it smartly finished after last digit. Thanks – ardabro Oct 29 '15 at 23:16

it is hard to answer without a sample.

try something like (can be onlined, no need for \ if last char is | )

  awk '{for(i=1;i<=NF;i++) 
     if ( substr($i,1,5) == "size:" ) { print substr($i,6) " " $0 ; next ; }}'  file |
    sort -n | awk '{$1="" ; print } '


  • first awk search for size field, and put it in front
  • sort with numeric argument
  • last awk remove numeric argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.