linux - Bash - 对文件中的行进行排序

标签 linux bash sorting range lines

各位溢出用户您好。

我很想知道如何在 Linux 中通过终端命令对文件中的一系列行进行排序。

例如在test.sh 文件中:

g++ -o test.out \
Main.cpp \
Framework.cpp \
Sample.cpp \
Blub.cpp \
-std=c++14 -lboost

如何从该文件的第二行到倒数第二行(源文件名)进行排序。

期望的输出:

g++ -o test.out \
Blub.cpp \
Framework.cpp \
Main.cpp \
Sample.cpp \
-std=c++14 -lboost

(从第 2 - 5 行排序)

感谢您的关注:)

最佳答案

使用 ex 行编辑器排序:

$ cat file
g++ -o test.out \
Sample.cpp \
Main.cpp \
Framework.cpp \
Blub.cpp \
-std=c++14 -lboost

$ echo 'x' | ex -s -c '2,5!sort' file

$ cat file
g++ -o test.out \
Blub.cpp \
Framework.cpp \
Main.cpp \
Sample.cpp \
-std=c++14 -lboost

ex -s -c '2,5!sort' 会将 ex 置于批处理模式(使用 -s)并应用命令 2,5!sort 到输入文件。这将通过对给定范围内的行执行外部 sort 实用程序,然后将相同的行替换为 sort 的输出来对第 2 行到第 5 行进行排序。

echo 'x' 用于将x 命令发送到ex,这将使它保存修改后的缓冲区并退出。否则,您将不得不在终端手动键入 x 并按 Enter 退出 ex

这假设经典的 ex(在 BSD 中找到)。如果你有来自 Vim 发行版的 ex,你可以使用

$ ex -s -c '2,5 sort|x' file

这使用 Vim 的 ex 中的内部排序命令(与 Vim 中的 :sort 相同)。


根据评论中的要求:

使用 BSD ex 对文件中从第 2 行到倒数第二行的所有行进行排序:

$ echo 'x' | ex -s -c '2,$-1!sort' file

或者,使用 Vim 的 ex:

$ ex -s -c '2,$-1 sort|x' file

范围从 2,5 变为 2,$-1,即从第 2 行变为“末尾减一”。


很遗憾,sed 不支持相同类型的操作。

关于linux - Bash - 对文件中的行进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46017946/

相关文章:

c - 为网卡实现内核旁路

linux - "Fatal: there are problems with fetch_image.cgi"使用 LabelMeAnnotationTool

arrays - 如何保持关联数组顺序?

sorting - golang排序 slice 升序或降序

java - JAVA和Python中的Windows排序顺序

java - 我可以使用表面对象在 Android 中制作显示对象吗?

linux - 在 Linux 上搜索文件中的错误编码字符

bash - 如何解决 shell 脚本 : "read: Illegal option -t"? 中的此错误

bash - 如何检查转换为小写的字符串是否等于 Bash 代码中的内容?

sorting - Magento 'Sort By' - 如何让 Magento 忘记选择了哪个选项