在linux中,我们可以运行sort命令来对文件内容进行排序,但在我的示例中,我有以下文件(THANKS.txt):
These people have contributed to OSN Envoy. We always try to keep this list updated and correct.
If you notice that your name is not listed here, then feel free to contact us.
Ar Rakin
Peter Williamson
David Brook
Bill Natt此文件包含软件项目贡献者的列表。
我只想用sort命令按字母顺序排序这些名字,有什么想法吗?
发布于 2022-03-04 13:03:12
使用awk:
awk '
NR == 1, NF == 0 {
# print and skip all lines until the first blank
# one (one where the Number of Fields is 0)
print; next
}
{print | "sort"} # pass the rest to sort
' < file将NF == 0替换为NR == 3,在第三行停止,而不是在第一行空白时停止。
为了避免其余部分同时通过awk和sort (也避免awk运行额外的shell来解释简单的sort命令行),您可以这样做:
{
sed '/[^[:blank:]]/!q'
sort
} < file其中,sed q在找到不包含(!)的第一行时会出现一个非空白字符。在第三行更改为sed 3q到quit。
但是,如果输入不可查找(比如来自管道的输入),sed将无法在该行分隔符之后将游标留在文件中,这意味着sort将错过sed可能读取的额外数据(因为它以较大块读取输入)。
使用sed的GNU实现,您可以为它添加-u选项,以便每次只读取一个字节的输入,这样就不会读取太多。
https://unix.stackexchange.com/questions/692920
复制相似问题