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

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

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

关于排序命令要记住的几个关键点是 -

  • 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

为了实际更改文件的内容,您可以使用下面显示的命令。

sortsomefile.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