如何在Linux中就地排序文件?


为了能够在Linux中对文件内容进行排序,我们首先必须了解Linux提供的**sort**命令。

sort命令主要用于对文件内容进行排序。它以特定方式排列记录。默认情况下,这些记录的排序是基于ASCII值。

关于sort命令,需要记住以下几点:

  • **SORT**命令一次对一行进行排序。

  • 当用于文件时,它会像**cat**命令一样打印文件的内容。

  • 它通常忽略大小写。

语法

sort filename

现在我们对sort命令有所了解,让我们来使用它。请考虑以下几个示例。

示例1

排序前的文件内容按此顺序排列。

immukul@192 d1 % cat somefile.txt
Is this text added
this file contains
a new text stream
and i am going to edit
that stream
yes i can do that
ask jeffrey

命令

sort filename.txt

输出

immukul@192 d1 % sort somefile.txt
Is this text added
a new text stream
and i am going to edit
ask jeffrey
that stream
this file contains
yes i can do that

我们可以看到,输出是基于ASCII编码排序的。

需要注意的是,输出肯定是排序后的,但文件的内容不会改变,我们可以使用cat命令再次打印文件内容来确认这一点。

immukul@192 d1 % cat somefile.txt
Is this text added
this file contains
a new text stream
and i am going to edit
that stream
yes i can do that
ask jeffrey

为了真正改变文件的内容,可以使用以下命令。

sort somefile.txt > anotherfile.txt

输出

immukul@192 d1 % cat anotherfile.txt
Is this text added
a new text stream
and i am going to edit
ask jeffrey
that stream
this file contains
yes i can do that

更新于:2021年7月31日

1K+ 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.