Sort entries of lines using shell

前端 未结 4 1515
-上瘾入骨i
-上瘾入骨i 2021-01-24 17:31

Considering the following input and output:

  infile   |   outfile
1 3 5 2 4  |  1 2 3 4 5
2 4 5      |  2 4 5
4 6 2 1    |  1 2 4 6

Is there a

4条回答
  •  遥遥无期
    2021-01-24 18:16

    Perl can do this nicely as a one-line Unix/Linux command:

    perl -n -e "print join ' ', sort{a<=>b} split ' '" < input.txt > output.txt
    

    This is "archaic" Perl with no dollars before the a and b, which allows the command to run fine in both Windows and bash shells. If you use the dollars with bash, they must either be escaped with backslashes, or you must invert the single and double quotes.

    Note that the distinctions you are trying to draw between commands, programming languages, and programs are pretty thin. Bash is a programming language. Perl can certainly be used as a shell. Both are commands.

    The reason your script runs slowly is that it spawns 3 processes per loop iteration. Process creation is pretty expensive.

提交回复
热议问题