我需要删除文本文件中的一串行,这些行是两个唯一字符串的偏移量。
输入
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做到这一点吗?
答案 0 :(得分:1)
我认为awk可以更轻松地解决这个问题:
awk '
/start of section/ { flag++ }
/start of section/,/end of section/ {
if ( flag == 1 ) {
print
}
next
}
{ print }
' infile
每次找到与start of section
匹配的行时,它会递增一个标志,并且每个部分都会检查此标志。在第二部分和后续部分的开头,flag
变量将具有大于1的值,并且将跳过它们而不进行打印。
它产生:
startdoc
apple
apple
start of section
WELCOME
this bunch of fruit
tastes like chicken
end of section
endoc
答案 1 :(得分:0)
这样的事情:
sed -n "1,/end of section/ p;$ p" file
这会将所有内容输出到第一部分的末尾,然后输出最后一行。