我在文本文件中循环遍历站名。对于文本文件中的每个站块,我想匹配第一次出现的“add”,并使用来自该站块的适当传感器和时间信息附加一个close语句。如果该站有第二个传感器,我还想在使用它的适当传感器和相同时间信息的第二次“添加”之后附加一个关闭语句。如果第二个传感器不存在,它可以移动到下一个站。我想在文本文件中的每个站块中遵循此模式。我用awk和sed尝试过一些东西,但是我只能在每次出现“add”后添加close语句。任何人都可以指导我采用更合适的技术吗?这是文本文件中的两个示例站点块:
sta charlie 34.07335 -106.91932 1.43 topico
time 01/14/2015 23:05:38
net XI SPREE
datalogger q330 0100000EA9C2B9C3 # 2842
sensor cmg3t 0 T3S82
add
sensor trillium 0 T3N04
add
#######Next station block###############
sta charlie2 34.07335 -106.91932 1.43 topico2
time 01/14/2015 23:05:38
net XI SPREE
datalogger q330 0100000EA9C2B9C3 # 2842
sensor trillium 0 T3S84
add
sensor sts2 0 T3N04
add
我希望代码输出以下内容:
sta charlie 34.07335 -106.91932 1.43 topico
time 01/14/2015 23:05:38
net XI SPREE
datalogger q330 0100000EA9C2B9C3 # 2842
sensor cmg3t 0 T3S82
add
close sensor cmg3t 01/14/2015 23:05:38
sensor trillium 0 T3N04
add
close sensor trillium 01/14/2015 23:05:38
#######Next station block###############
sta charlie2 34.07335 -106.91932 1.43 topico2
time 01/23/2015 17:04:22
net XI SPREE
datalogger q330 0100000EA9C2B9C3 # 2842
sensor trillium 0 T3S84
add
close sensor trillium 01/23/2015 17:04:22
sensor sts2 0 T3N04
add
close sensor sts2 01/23/2015 17:04:22
答案 0 :(得分:2)
像这样的东西听起来像你想要的但是当所有输入的日期为1/14时,你发布的输出中的日期变成了1/23:
$ awk '/^time/{time=$2" "$3} /^sensor/{sensor=$1" "$2} {print} /^add/{print "close", sensor, time}' file
sta charlie 34.07335 -106.91932 1.43 topico
time 01/14/2015 23:05:38
net XI SPREE
datalogger q330 0100000EA9C2B9C3 # 2842
sensor cmg3t 0 T3S82
add
close sensor cmg3t 01/14/2015 23:05:38
sensor trillium 0 T3N04
add
close sensor trillium 01/14/2015 23:05:38
#######Next station block###############
sta charlie2 34.07335 -106.91932 1.43 topico2
time 01/14/2015 23:05:38
net XI SPREE
datalogger q330 0100000EA9C2B9C3 # 2842
sensor trillium 0 T3S84
add
close sensor trillium 01/14/2015 23:05:38
sensor sts2 0 T3N04
add
close sensor sts2 01/14/2015 23:05:38