我有这样的文件内容:
aaa accounting exec ...
aaa accounting exec ...
aaa accounting commands ..
aaa accounting commands ..
aaa accounting commands ..
aaa accounting commands ..
aaa accounting commands ..
aaa accounting commands ..
aaa accounting network ..
aaa accounting connection ..
aaa accounting system ..
!
aaa accounting exec default
action-type start-only
group tacacs+
!
aaa accounting exec default stop-only group tacacs+输出应该如下:
aaa accounting exec default ..
aaa accounting exec default
action-type start-only
group tacacs+
!
aaa accounting exec default ..我尝试了以下sed命令:
sed -n '/aaa accounting exec default/,/!/p' AboveFileContent.txt但这不是我想要的。
解决办法是什么?我也尝试过使用awk,但同样的结果即将到来。得到准确输出的命令是什么?
发布于 2014-12-23 14:59:44
我会用awk来做这个:
awk '
/aaa accounting exec default/ {print; exec=1; next}
exec {
if (/^ /) {print; next} else if (/^!/) {print}
exec=0
}
' filename传递模式,使用awk的-v选项,然后模式匹配操作符~:
awk -v patt='aaa accounting exec default' '
$0 ~ patt {print; exec=1; next}
exec {
if (/^ /) {print; next} else if (/^!/) {print}
exec=0
}
' filename发布于 2014-12-23 14:48:23
您正在尝试将数据结构化为以下形式:
aaa ...
...
...
!您需要让sed意识到缩进块很重要。一种简单的方法可能是用sed编写一个循环:
sed -n '
# Create a label named 'start'
:start
# If the line matches the beginning of a block,
# jump (branch) to the label named section
/aaa accounting exec default/ b section
# If we didn't branch, get the next line
n
# Jump back to the start label
b start
# The label named section
:section
# print the line
p
n
# Keep looping to section for the lines we need
/^ /,/!/ b section
# If we don't have any more lines to loop on,
# jump back to the beginning
b start
'一行:
$ sed -n ':start; /aaa accounting exec default/ b section; n; b start; :section; p; n; /^ /, /!/ b section; b start' test.txt
aaa accounting exec default start-stop group tacacs+
aaa accounting exec default
action-type start-only
group tacacs+
!
aaa accounting exec default stop-only group tacacs+我想,可以使用awk、perl或python,以一种更易读的方式来完成。
https://askubuntu.com/questions/564668
复制相似问题