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

Bash - sort range of lines in file

嗨,溢出用户。

我很想知道如何通过 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 行排序)

感谢您的关注:)

有头、GNU sed 和尾:

(head -n 1 test.sh; sed -n '2,${/\/p}' test.sh | sort; tail -n 1 test.sh) > test_new.sh

输出:

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

编辑vi中的文件时,光标在Blub.cpp处,可以输入

:.,+3 !sort

或者当你不想计算行数时,使用另一个范围:

:.,/std/-1 !sort

编辑: 来自命令行:

ex -c'2,5 sort|w|q' test.sh

使用 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'用于向ex发送x命令,使它保存修改后的缓冲区并退出。否则,您将不得不在终端手动输入 x 并按 Enter 退出 ex.

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

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

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


根据评论中的要求:

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

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

或者 Vim 的 ex:

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

范围从 2,5 更改为 2,$-1,即从第 2 行更改为 "the end minus one"。


可惜sed不支持同类型操作

$ cat test.awk
{ a[NR]=[=10=] }
END { 
    print a[1]
    lastline=a[NR]
    delete a[1]
    delete a[NR]
    n=asort(a)
    for (i = 1; i <= n; i++) { print a[i] }
    print lastline
}
  • a[NR]=[=12=] : 将文件的行加载到数组 a 中;使用 line/record 数字 (NR) 作为数组索引
  • END { ... } :将所有行加载到数组后,对数组应用以下命令 ...
  • print a[1] : 打印第 1 行
  • lastline=a[NR] :将最后一行保存在变量 lastline
  • delete a[#] : 从数组中删除第一行和最后一行
  • n=asort(a) :对数组中剩余的行进行排序,将数组项的数量(即数组中剩余的行数)分配给我们的变量 n
  • for/print :打印第 2 行 - 倒数第二行
  • print lastline : 打印最后一行

现在 运行 针对示例文件:

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