簡體   English   中英

在Bash中按字母順序排序

[英]Sorting alphabetically in Bash

我有一個包含以下數據的文件:

adam
humanities

castiel
sciences

antwon
sciences

dmitri
informatics

zoe
mathematics

bernard
economics

我希望能夠根據人員的名字對文件進行排序,以便輸出如下所示:

adam
humanities

antwon
sciences

bernard
economics

castiel
sciences

dmitri
informatics

zoe
mathematics

cat filename | sort cat filename | sort對包括主題在內的所有數據cat filename | sort排序。 我如何用人名來排序?

awk中使用asorti對數據數組進行排序

awk '{a[$1]=$2} 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

如果你的awk沒有asorti ,試試這個:

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

這是一個非常殘酷的解決方案,但工作...... :)你可以讓它看起來更好。 主要想法是創造

<name>|<occupation>\n 

列表,並對其進行排序,而不是使其看起來像原始。

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

使用awk - 剝去空行並打印由冒號分隔的每條記錄。 然后排序然后使用awk打印所需格式的記錄。

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

這可能適合你(GNU sed):

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

刪除空白行。 在模式空間中讀取兩行。 用空格替換換行符。 排序文件。 替換換行符並添加空行。

如果你的名字包含空格,那么不漂亮並且不會起作用...你可能想要一個perl解決方案以一種理智和可讀的方式做到這一點。

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

antwon
sciences

bernard
economics

castiel
sciences

dmitri
informatics

zoe
mathematics

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM