Numerically sorting strings from file

时间:2015-05-24 20:32:18

标签: bash

Thing is, I would like to numerically sort those strings from file, without changing content of the file. Strings in file must not be changed after sorting operation. I want to use lines for editing them later, so my variable var should get values starting with 0:wc...'till 200:wc.

Input:

11:wc
1:wc 
0:wc
200:wc

Desired order:

0:wc
1:wc
11:wc
200:wc

I'm using this code, but has no effect:

sort -k1n $1 | while read line
  do
   if [[ ${line:0:1} != "#" ]] 
    then
    var=$line
   fi
 done <$1

3 个答案:

答案 0 :(得分:1)

Why not just

$ sort -k1n -t: file.txt

specifying the field separator as ':'.

答案 1 :(得分:0)

Two issues:

  1. When you create a pipe, such as command | while read line; do ... end, the individual commands in the pipe (command and while read line; do ... end) run in subshells.

    The subshells are created with copies of all the current variables, but are not able to reflect changes back into their parent. In this case line is only present in the subshell, and when the subshell terminates, it disappears with it.

    You can use bash process substitution to avoid creating a subshell for one of the pipeline commands. For example, you could use:

     while read line; do ... end < <(command)
    
  2. If you both pipe and redirect, the redirect wins.

    So when you write: command | while read line; do ... end < input, the while loop actually reads from input, not from the output of command.

答案 2 :(得分:0)

You need to sort numerically on the first key, and if you need them for later, just read them into an array:

myarray=( $(sort -k1n <file) )

which will provide an array with sorted contents:

0:wc
1:wc
11:wc
200:wc