有一个类似格式的文件:
# Lorem ipsum dolor sit amet, consectetur adipiscing elit.
# Donec vitae ex metus. Integer nec dui sit amet odio vehicula tincidunt ac eget justo.
#
[A8-LINER-ADJUSTEMENT]
type: q-first-party
id: 3.4.987
canOperate: true
hash: 9bf533ef77fddb43cdc4b96ca9eb68fc862d71e90bb05b98abc9d1050893c266
[A8-LINER-ADJUSTEMENT]
type: q-first-party
id: 5.2.987
canOperate: true
hash: c8939c165c3af4ae77e7d5030b43644721fb8225e2994e846ef129f7de49254b
[A8-LINER-ADJUSTEMENT]
type: q-third-party
id: 4.9.987
canOperate: false
hash: f9ddaeaad5ed2280fbb9660553ab0af8bf6ea0a5a4b0db432398f26470e557bf
目标是删除
[A8-LINER-ADJUSTEMENT]
(含)和空行(含)之间的全部内容。而属性 type
是 q-third-party
。
命令执行后的文件应如下所示:
# Lorem ipsum dolor sit amet, consectetur adipiscing elit.
# Donec vitae ex metus. Integer nec dui sit amet odio vehicula tincidunt ac eget justo.
#
[A8-LINER-ADJUSTEMENT]
type: q-first-party
id: 3.4.987
canOperate: true
hash: 9bf533ef77fddb43cdc4b96ca9eb68fc862d71e90bb05b98abc9d1050893c266
[A8-LINER-ADJUSTEMENT]
type: q-first-party
id: 5.2.987
canOperate: true
hash: c8939c165c3af4ae77e7d5030b43644721fb8225e2994e846ef129f7de49254b
sed -i '/\[A8-LINER-ADJUSTEMENT\]/,/^$/ { /q-third-party/d; }' introduction-availe.dat
此命令仅删除
type: q-third-party
行,因为预期会删除指定范围内的内容。
只是为了好玩..如果你在服务器上安装了
PHP
..这就能解决问题..有1001种方法可以通过编程来完成此操作..我只是选择PHP,因为它易于使用explode()
<?php
$file = file_get_contents("introduction-availe.dat");
$items = explode('[', $file);
$file_header = $items[0];
array_shift($items);
$new_file = "$file_header\n";
foreach($items as $item){
$item = '[' . $item;
$sub_items = array_filter( explode("\n", $item) );
if($sub_items[1] != 'type: q-third-party'){
foreach($sub_items as $sub_item){
$new_file .= "$sub_item\n";
}
$new_file .= "\n";
}
}
$f=fopen('introduction-availe.dat','w');
fwrite($f,$new_file);
fclose($f);
当 he 标签之外没有
[
字符时,您可以创建一个丑陋的 sed
解决方案
sed -z 's/\[A8-LINER-ADJUSTEMENT\][^[]*type: q-third-party[^[]*//g' file
[^[]*
是一组字符[]
,除了[
之外的所有内容,所以^[
,重复0次或多次*
。