[英]Use sed/awk to delete a line if the following line does not match
I have a list of data as follows: 我有如下数据列表:
Account Number: 11111
Domain : domain.com
Quantity: 1
Quantity: 2
Processor: Intel Xeon E5-1650 V2 3.5GHZ, Hexa Core
SERVERCHASSIS: Standard - Single PSU - No Hot Swap Bays
Account Number: 54321
Domain : domain0.com
Quantity: 1
Processor: Intel Xeon E3-1240 V1 3.3Ghz, Quad Core
SERVERCHASSIS: Standard - Single PSU - No Hot Swap Bays
Quantity: 1
Account Number: 12345
Domain : domain1.com
Quantity: 1
I would like to use sed/awk to delete all entries of "Quantity: X" that are not followed by "Processor:" on the next line. 我想使用sed / awk删除下一行中不跟随“ Processor:”的所有“ Quantity:X”条目。 I would also like to remove "Account Number: XXXXX" and "Domain:" lines if the lines following do not contain both "Quantity: X" and "Processor:". 如果下面的行同时不包含“数量:X”和“处理器:”,我还想删除“帐号:XXXXX”和“域:”行。 This in turn would change the above data to: 依次将上述数据更改为:
Account Number: 11111
Domain : domain.com
Quantity: 2
Processor: Intel Xeon E5-1650 V2 3.5GHZ, Hexa Core
SERVERCHASSIS: Standard - Single PSU - No Hot Swap Bays
Account Number: 54321
Domain : domain0.com
Quantity: 1
Processor: Intel Xeon E3-1240 V1 3.3Ghz, Quad Core
SERVERCHASSIS: Standard - Single PSU - No Hot Swap Bays
Can anyone provide a way to complete this task using sed or awk or a combination of both? 任何人都可以提供使用sed或awk或两者结合来完成此任务的方法吗?
$ cat tst.awk
BEGIN{ RS=""; FS="\n" }
/Quantity:/ && /Processor:/ {
for (i=1; i<=NF; i++) {
if ( ! (($i ~ /Quantity:/) && ($(i+1) !~ /Processor:/)) ) {
print $i
}
}
print ""
}
$
$ awk -f tst.awk file
Account Number: 11111
Domain : domain.com
Quantity: 2
Processor: Intel Xeon E5-1650 V2 3.5GHZ, Hexa Core
SERVERCHASSIS: Standard - Single PSU - No Hot Swap Bays
Account Number: 54321
Domain : domain0.com
Quantity: 1
Processor: Intel Xeon E3-1240 V1 3.3Ghz, Quad Core
SERVERCHASSIS: Standard - Single PSU - No Hot Swap Bays
EDIT: Erf... Should have read the question before answering. 编辑:Erf ...在回答之前应该已经阅读了问题。
This one should work, hopefully 希望这个可以工作
BEGIN {
OFS=RS
FS="\n"
RS= ""
}
{
selected = 0
drop = 0
for (i = 1; i <= NF ; i++)
{
if ($i ~ "Quantity:")
{
if ($(i+1) ~ "Processor:") selected = 1
else drop++
}
$i = $(i+drop)
}
if (selected) print
}
cmd 命令
gawk -f processor.awk processor.txt
output 输出
Account Number: 11111
Domain : domain.com
Quantity: 2
Processor: Intel Xeon E5-1650 V2 3.5GHZ, Hexa Core
SERVERCHASSIS: Standard - Single PSU - No Hot Swap Bays
Account Number: 54321
Domain : domain0.com
Quantity: 1
Processor: Intel Xeon E3-1240 V1 3.3Ghz, Quad Core
SERVERCHASSIS: Standard - Single PSU - No Hot Swap Bays
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.