Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 基于两个字符串的偏移量删除一段文本_String_Sed_Awk - Fatal编程技术网

String 基于两个字符串的偏移量删除一段文本

String 基于两个字符串的偏移量删除一段文本,string,sed,awk,String,Sed,Awk,我需要删除文本文件中的一组行,这些行是两个唯一字符串的偏移量 输入 startdoc apple apple start of section WELCOME this bunch of fruit tastes like chicken end of section start of section chapter1 I have all the orange in the world end of section e

我需要删除文本文件中的一组行,这些行是两个唯一字符串的偏移量

输入

startdoc
  apple
  apple
  start of section
    WELCOME
    this bunch of fruit 
    tastes like chicken
  end of section
  start of section
    chapter1
    I have all the orange 
    in the world
  end of section
endoc
输出

startdoc
  apple
  apple
  start of section
    WELCOME
    this bunch of fruit 
    tastes like chicken
  end of section
endoc
从上面的示例中,要删除的第一行是第9行到第13行。基本上,删除第一部分

我尝试使用行号说明符使用sed,但行号会因不同的文件而改变

理想情况下,如果我指定sed从“chapter1”之前的行开始删除,并指定sed在“enddoc”之前的行停止删除。起点和终点的偏移量为-1行。有什么办法可以通过sed做到这一点吗?

类似这样的方法:

sed -n "1,/end of section/ p;$ p" file 
这会将所有内容输出到第一节的末尾,然后再输出最后一行。

我认为这样可以更轻松地处理此问题:

awk '
    /start of section/ { flag++ } 
    /start of section/,/end of section/ { 
        if ( flag == 1 ) { 
            print 
        } 
        next 
    } 
    { print }
' infile
每当它找到与节的开头匹配的行时,它就会增加一个标志,并为每个节检查该标志。在第二节和后续章节的开头,
标志
变量的值将大于1,并且将跳过它们而不打印

它产生:

startdoc
  apple
  apple
  start of section
    WELCOME
    this bunch of fruit 
    tastes like chicken
  end of section
endoc

我不明白。删除基于第二节的第一节的条件是什么?@Birei,我在示例中犯了一个错误,已更正。我想保留第一部分,并去掉所有后续部分。