在 Bash 中按字母顺序排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18374545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:21:28  来源:igfitidea点击:

Sorting alphabetically in Bash

bashsortingsedawk

提问by rahuL

I have a file with the following data in it:

我有一个包含以下数据的文件:

adam
humanities

castiel
sciences

antwon
sciences

dmitri
informatics

zoe
mathematics

bernard
economics

I want to be able to sort the file w.r.t the names of the people so that the output looks like so:

我希望能够根据人员姓名对文件进行排序,以便输出如下所示:

adam
humanities

antwon
sciences

bernard
economics

castiel
sciences

dmitri
informatics

zoe
mathematics

cat filename | sortsorts all the data including the subjects. How do I sort it with the names of people?

cat filename | sort对包括主题在内的所有数据进行排序。我如何用人名排序?

回答by Jotne

Using asortiin awkto sortthe array of data

awk中使用asorti对数据数组进行排序

awk '{a[]=} END {n=asorti(a,c);for (i=1;i<=n;i++) print c[i] "\n" a[c[i]] "\n"}' RS= file
adam
humanities

antwon
sciences

bernard
economics

castiel
sciences

dmitri
informatics

zoe
mathematics

If your awkdoes not have asorti, try this:

如果你的awk没有asorti,试试这个:

awk '{print ,}' RS="" file | sort | awk '{print  "\n"  "\n"}'

回答by csikos.balint

It is a quite brutal solution, but works... :) You can make it look better. The main idea is to create

这是一个非常残酷的解决方案,但有效...... :) 你可以让它看起来更好。主要思想是创造

<name>|<occupation>\n 

list, and sort it than make it look as the original.

列表,并对它进行排序,而不是让它看起来像原来的一样。

cat /tmp/delme | sed -e ':a;N;$!ba;s/\n/|/g' | sed -e 's/||/\n|/g' | sort | sed -e 's/|/\n/g'

回答by suspectus

Use awk - strip the empty lines and print each record separated by colon say. Then sort and then using awk print the record in the required format.

使用 awk - 去除空行并打印每个以冒号分隔的记录。然后排序,然后使用 awk 以所需格式打印记录。

awk -v RS="" -F"\n" '{print  ":" }' e | sort | awk -v FS=":" '{print  "\n"  "\n"}'

回答by potong

This might work for you (GNU sed):

这可能对你有用(GNU sed):

sed '/./!d;$!N;s/\n/ /' file | sort | sed 's/ /\n/g;$!G'

Drop blank lines. Read two lines into the pattern space. Replace newline with space. Sort file. The replace the newlines and add in blank lines.

删除空行。将两行读入模式空间。用空格替换换行符。排序文件。替换换行符并添加空行。

回答by Adrian Frühwirth

Not pretty and won't work if your names contain spaces...you probably want a perlsolution to do this in a sane and readable way.

不漂亮,如果您的名称包含空格,则不起作用……您可能需要一个perl解决方案以一种理智和可读的方式来做到这一点。

$ awk -v RS='\n\n' '{ print ,  }' foo.input | sort | sed -e 's#$#\n#g' -e 's# #\n#g'
adam
humanities

antwon
sciences

bernard
economics

castiel
sciences

dmitri
informatics

zoe
mathematics