且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Bash中的2种模式之间按字母顺序对行进行排序

更新时间:2023-01-20 17:18:10

这是使用

This is a perfect case to use asort() to sort an array in GNU awk:

gawk '/PATTERN1/ {f=1; delete a}
      /PATTERN2/ {f=0; n=asort(a); for (i=1;i<=n;i++) print a[i]}
      !f
      f{a[$0]=$0}' file

这使用了与如何在两个标记模式之间选择行(使用awk/sed可能多次发生)类似的逻辑加上:

This uses a similar logic as How to select lines between two marker patterns which may occur multiple times with awk/sed with the addition that it:

  • 打印超出此范围的行
  • 存储此范围内的行
  • 当范围结束时,对其进行排序和打印.

详细说明:

  • /PATTERN1/ {f=1; delete a}当找到与PATTERN1匹配的行时,将一个标志设置为on,并清除行数组.
  • /PATTERN2/ {f=0; n=asort(a); for (i=1;i<=n;i++) print a[i]}当找到与PATTERN2匹配的行时,将标志设置为off.另外,对包含该范围内所有行的数组a[]进行排序并打印它们.
  • !f如果该标志处于关闭状态(即超出范围),则求值为True,以便打印该行.
  • f{a[$0]=$0}如果该标志处于打开状态,则将该行存储在数组a[]中,以便以后可以使用其信息.
  • /PATTERN1/ {f=1; delete a} when finding a line matching PATTERN1, sets a flag on, and clears the array of lines.
  • /PATTERN2/ {f=0; n=asort(a); for (i=1;i<=n;i++) print a[i]} when finding a line matching PATTERN2, sets the flag off. Also, sorts the array a[] containing all the lines in the range and print them.
  • !f if the flag is off (that is, outside the range), evaluate as True so that the line is printed.
  • f{a[$0]=$0} if the flag is on, store the line in the array a[] so that its info can be used later on.
▶ gawk '/PATTERN1/ {f=1} /PATTERN2/ {f=0; n=asort(a); for (i=1;i<=n;i++) print a[i]} !f; f{a[$0]=$0}' FILE
aaa
bbb
PATTERN1
bar
baz
foo
qux
PATTERN2
ccc
ddd