sed
为此目的提供了一个脚本:
翻译.sed:
:a
/Module/ {
x
s/.*Module (.*)/[End Module="\1"]/p
x
h
s/(--- )(.*)/[Start Module="\2"]/p
:b
n
/Module/! {
s/(\s*)(.*)/\1[Message Content="\2"]/p
bb
}
/Module/ {
$!ba
h
s/(--- )(.*)/[Start Module="\2"]/p
x
s/.*Module (.*)/[End Module="\1"]/p
}
}
像这样执行它:
sed -nrf translate.sed file.txt
输出:
[Start Module="Module A"]
[Message Content="Info: indented message 1"]
[Message Content="Note: indented message 2"]
[Message Content="Warning: indented message 3"]
[End Module="A"]
[Start Module="Module B"]
[End Module="B"]
[Start Module="Module C"]
[Message Content="Info: indented message 1"]
[End Module="C"]
[Start Module="Module D"]
这是相同版本的脚本,并添加了解释:
翻译.sed
# Define lable 'a' to iterate over modules
:a
# If the line module is matched ...
/Module/ {
# Swap contents of hold and pattern buffer (current line)
x
# If the pattern buffer (former hold buffer)
# contains something it is a module starting line.
# Create and end tag out of it.
s/.*Module (.*)/[End Module="\1"]/p
# Get the current line back from hold buffer
x
h
# Create a start module tag
s/(--- )(.*)/[Start Module="\2"]/p
# Create a label to iterate over messages
:b
# Get next line from input into pattern buffer
# (Overwrite the pattern buffer)
n
# If it is not a module starting line ...
/Module/! {
# ... wrap it into the Message Content tag
s/(\s*)(.*)/\1[Message Content="\2"]/p
# and go on with the next line (step back to b)
bb
}
/Module/ {
# if it is not the last line
# go on with the next module (step back to a)
$!ba
# on the last line ...
# backup the current line in the hold buffer
h
# create start tag
s/(--- )(.*)/[Start Module="\2"]/p
# swap hold and pattern buffer
x
# create the end tag
s/.*Module (.*)/[End Module="\1"]/p
}
}
顺便说一句,它当然也可以是单线:D
sed -rn ':a;/Module/{;x;s/.*Module(.*)/[EndModule="\1"]/p;x;h;s/(---)(.*)/[StartModule="\2"]/p;:b;n;/Module/!{;s/(\s*)(.*)/\1[MessageContent="\2"]/p;;bb;};/Module/{;$!ba;h;s/(---)(.*)/[StartModule="\2"]/p;x;s/.*Module(.*)/[EndModule="\1"]/p;};};' file.txt