0

I'm new to linux and checking to see if there is any sort command available for below scenario. I have a file containing lines like below.

this is a 10

this is 5

this 40

this is a boy in 3

this is a boy 6

I would like to sort it like

this 40

this is 5

this is a 10

this is a boy 6

this is a boy in 3

Any help is appreciated!

Barro
  • 335
  • 3
  • 16

2 Answers2

1

Assuming all of your data is in a text file called testfile this answer should work:

cat testfile | awk '{ print length, $0 }' | sort -n | cut -d" " -f2-

It comes from this question: Sort a text file by line length including spaces

Community
  • 1
  • 1
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
  • 1
    Should have searched; came up with the exact same solution 2 minutes after you posted. +1 for search-foo – Andrew White Dec 06 '13 at 04:14
  • I want to do this alphabetically - for example chilworth 3 chilworth and 1 chimaeren 1 chimaeren is 2 – Barro Dec 06 '13 at 04:21
  • @Barro Your question doesn’t have those as an example. And that would need to have the logic changed. Also, you just said in your comments, “Jerry yes, by length of the lines.” So unclear what your new requirement is coming from. – Giacomo1968 Dec 06 '13 at 04:29
  • Jake sorry abt tht. I should have mentioned the word alphabetically by length of lines. – Barro Dec 06 '13 at 04:38
  • @Barro if you just want to sort `testfile` alphabetically, then all you need is `sort testfile` – janos Dec 06 '13 at 05:39
0

If you don't care about blank lines you can run

$ sort <filename>




this 40
this is 5
this is a 10
this is a boy 6
this is a boy in 3

sort can read a file and organize the output. If you want to remove the empty lines, one option you have is sed

$ sort test.txt | sed '/^$/d'
this 40
this is 5
this is a 10
this is a boy 6
this is a boy in 3