BASH 2模式之间按字母顺序排序线 [英] BASH sort alphabetically lines between 2 patterns
本文介绍了BASH 2模式之间按字母顺序排序线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按字母顺序排序仅2模式之间的线/ ^ BLE BLE BLE /和/ ^ CCC DDD EEE /。重要的是,我要离开休息线完整(不排序)。
I'd like to sort alphabetically only lines between 2 patterns /^ble ble ble/ and /^ccc ddd eee/. Important thing is that I want to leave rest lines intact ( not sorted ).
例CFG文件:
123 345
678 901
bla bla bla
ble ble ble
crypto isakmp key 6 CCCCCC address 123.456.789.004
crypto isakmp key 6 AAAAAA address 123.456.789.005
crypto isakmp key 6 XXXXXX address 123.456.789.003
crypto isakmp key 6 BBBBBB address 123.456.789.001
ccc ddd eee
fff ggg hhh iii
123 456
期望的输出:
123 345
678 901
bla bla bla
ble ble ble
crypto isakmp key 6 AAAAAA address 123.456.789.005
crypto isakmp key 6 BBBBBB address 123.456.789.001
crypto isakmp key 6 CCCCCC address 123.456.789.004
crypto isakmp key 6 XXXXXX address 123.456.789.003
ccc ddd eee
fff ggg hhh iii
123 456
preferred工具AWK和单行。将是很好,如果解释附会。
Preferred tool is AWK and "one-liner". Would be nice if explanation will be attached.
问候,
迈克
推荐答案
这是使用的 ASORT()
以按GNU AWK数组:
This is a perfect case to use asort()
to sort an array in GNU awk:
gawk '/^ble/ {f=1}
/^ccc ddd eee/ {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:
- 此范围之外的打印线
- 此范围内的房屋线
- 当档已经结束,排序和打印他们。
详细说明:
-
/ ^ BLE / {F = 1}找到先从
BLE
A线的时候,就设置一个标志 -
/ ^ CCC DDD EEE / {F = 0; N = ASORT(一);对于(i = 1; I&LT; = N;我++)打印[I]}发现开始
,设置该标志关闭。此外,排序的数组CCC DDD EEE
A线的时候A []
包含该范围内的所有线路,并打印出来。 -
!˚F
如果标志是关闭(即超出范围),使该行打印,评估为true。 -
˚F{a [$ 0] = $ 0}
如果标志是,存储阵列中的行A []
,以便其信息可以在以后使用。
/^ble/ {f=1}
when finding a line starting withble
, set a flag on./^ccc ddd eee/ {f=0; n=asort(a); for (i=1;i<=n;i++) print a[i]}
when finding a line starting withccc ddd eee
, set the flag off. Also, sort the arraya[]
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 arraya[]
so that its info can be used later on.
$ gawk '/^ble/ {f=1} /^ccc ddd eee/ {f=0; n=asort(a); for (i=1;i<=n;i++) print a[i]} !f; f{a[$0]=$0}' a
123 345
678 901
bla bla bla
ble ble ble
crypto isakmp key 6 AAAAAA address 123.456.789.005
crypto isakmp key 6 BBBBBB address 123.456.789.001
crypto isakmp key 6 CCCCCC address 123.456.789.004
crypto isakmp key 6 XXXXXX address 123.456.789.003
ccc ddd eee
fff ggg hhh iii
123 456
这篇关于BASH 2模式之间按字母顺序排序线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文