Search code examples
sortingcommand-linels

On command-line how to start sorting from nth index in ascending order


=> "ls" command always outputs in ascending order:

common_results /1_L_0.010293_O=3.4077_B=1_SR=1.1349_500/ test.txt

common_results /1_L_0.010588_O=0.24208_B=0_SR=0.70094_500/ test.txt

common_results /1_L_0.011283_O=1.6461_B=0_SR=0.86875_500/ test.txt

common_results /1_L_0.011446_O=2.9968_B=0_SR=0.74779_500/ test.txt

common_results /1_L_0.011487_O=8.5498_B=0_SR=0.84261_500/ test.txt

=> Will it be be possible to do "ls" starting ascending from nth index point. For example from 29th index point where it will starting ascending from character next to "_O="

"ls" (updated result.)

common_results /1_L_0.010588_O=0.24208_B=0_SR=0.70094_500/test.txt

common_results /1_L_0.010293_O=3.4077_B=1_SR=1.1349_500/test.txt

common_results /1_L_0.011446_O=2.9968_B=0_SR=0.74779_500/test.txt

common_results /1_L_0.011487_O=8.5498_B=0_SR=0.84261_500/test.txt

common_results /1_L_0.011283_O=1.6461_B=0_SR=0.86875_500/test.txt


Solution

  • It's not always a good idea to parse the output of ls but, provided you understand the consequences (it can be full of all sorts of wondrous characters like spaces or newlines, all of which will cause simplistic assumptions to fail) and can mitigate the problems, you can pass the file names through sort to get the effect you want:

    pax> #   1         2         3         4
    pax> #7890123456789012345678901234567890
    pax> #                        V
    pax> echo '
    common_results/1_L_0.010293_O=3.4077_B=1_SR=1.1349_500/test.txt
    common_results/1_L_0.010588_O=0.24208_B=0_SR=0.70094_500/test.txt
    common_results/1_L_0.011283_O=1.6461_B=0_SR=0.86875_500/test.txt
    common_results/1_L_0.011446_O=2.9968_B=0_SR=0.74779_500/test.txt
    common_results/1_L_0.011487_O=8.5498_B=0_SR=0.84261_500/test.txt' | sort  -k1.31
    
    common_results/1_L_0.010588_O=0.24208_B=0_SR=0.70094_500/test.txt
    common_results/1_L_0.011283_O=1.6461_B=0_SR=0.86875_500/test.txt
    common_results/1_L_0.011446_O=2.9968_B=0_SR=0.74779_500/test.txt
    common_results/1_L_0.010293_O=3.4077_B=1_SR=1.1349_500/test.txt
    common_results/1_L_0.011487_O=8.5498_B=0_SR=0.84261_500/test.txt
    

    That sorts the output based on the first field, thirty-first character (both one-based) which is the position of the character following O=.

    You may also want to use the -n numeric flag for sort if there's the possibility of numbers greater than or equal to ten. Without that, 27.1828 will be considered less than 3.14159.