简体   繁体   English

Bash - Awk排序 - 不排序

[英]Bash - Awk sort -n not sorting

awk '{for(i=1; i<=NF; i++) printf("%d ",$i)}' | sort -n

it reads a file like 它读取的文件就像

55 89 33 20

and prints it out normally, not numerically sorted. 并正常打印出来,而不是按数字排序。 Why? 为什么?

sort works on a per-line basis, and printf doesn't append a newline by default, you need to specify it. sort按行进行,默认情况下printf不附加换行符,您需要指定它。 So use: 所以使用:

awk '{for(i=1; i<=NF; i++) printf("%d\n",$i)}' | sort -n

This will print out your numbers on separate lines, if you want them to be in a single line again then you can pipe it to paste : 这将在单独的行中打印出您的数字,如果您希望它们再次在一行中,那么您可以将其管道paste

awk '{for(i=1; i<=NF; i++) printf("%d\n",$i)}' | sort -n | paste -s -d ' '

You can also just use print instead of printf, this will append the newline by default: 您也可以使用print而不是printf,默认情况下会附加换行符:

awk '{for(i=1; i<=NF; i++) print $i}' | sort -n

If you want to keep the numbers all on one line but sort them, you can also just do the sorting in awk itself. 如果你想将数字全部保存在一行但是对它们进行排序,你也可以在awk进行排序。

$ awk '{split($0,f,FS); n=asort(f); 
     for (i=1; i<=n; ++i) printf("%d ", f[i]); printf "\n"}' <<<'55 89 33 20'
20 33 55 89

But this is starting to get into territory where I reach for Perl instead, just because it's a shorter program to write at the shell prompt: 但是我开始进入Perl的领域,只是因为它是一个在shell提示符下编写的更短的程序:

$ perl -lane 'print join " ",sort @F' <<<'55 89 33 20'
20 33 55 89

Awk is more expressive in many cases, but array operations are not one of them. 在许多情况下,awk更具表现力,但阵列操作不是其中之一。

Ruby is about as short, if you prefer a language that was cool more recently than Perl :) : 如果你喜欢一种比Perl更酷的语言,Ruby就差不多了:):

$ ruby -lane 'puts $F.sort.join " "' <<<'55 89 33 20'
20 33 55 89

Even Python, which is not exactly built for one-liners, is less code than Awk in this case (but the same number of parentheses): 在这种情况下,即使Python不是专为单行编写的,也不是Awk的代码(但括号相同):

$ python -c 'print " ".join(sorted(raw_input().split()))' <<<'55 89 33 20'
20 33 55 89

Setting the file as per your example: 根据您的示例设置文件:

echo "55 89 33 20" > file.txt

The following command will output what you want: 以下命令将输出您想要的内容:

awk '{for(i=1; i<=NF; i++) print($i)}' file.txt | sort -n
20
33
55
89

Note that print will print a new line character each time. 请注意, print每次都会打印一个换行符。
Also, note that the filename should be passed as an argument to awk . 另请注意,文件名应作为参数传递给awk

没有awk的解决方案:

cat file | sed 's/ /\n/g' | sort -n | paste -s -d ' '

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM