如何用sed中的单行替换两个模式之间的行? [英] How do I replace lines between two patterns with a single line in sed?
问题描述
这是我的输入文件:
one
two
three
four
five
six
seven
eight
nine
ten
我想把文件变成
one
two
three
NEW LINE
eight
nine
ten
与sed.也就是说,我想用单行NEW LINE
替换从/four/
(包括)到/seven/
(包括)的行.
我可以做到
sed '/four/aNEW LINE
/four/,/seven/d' file.txt
但是我想知道是否有一种更简单的方法,尤其是一种无需重复模式的方法(就像我对/four/
所需要的那样).
编辑根据 fedorquis 的评论问题,这也可能是awk(尽管出于学术"目的,我会对sed解决方案感兴趣.)>
编辑2 不幸的是,输入文件表明输入文件中的单词具有逻辑顺序(一个后跟两个通过三个等).但是,在我的现实世界"问题中,情况并非如此.我不知道文件有多少行,四和七行之前或之后是什么.我所知道的唯一的事情是,有一行 four (不一定立即)紧跟着一行 7 .我很抱歉在提出问题时没有明确说明这一点,尤其是因为 fedorqui 在他的回答上花了很多心血.
这可能对您有用(GNU sed& bash):
sed $'/^four/{:a;N;/^seven/McNEWLINE\nba}' file
This is my input file:
one
two
three
four
five
six
seven
eight
nine
ten
I want to turn the file into
one
two
three
NEW LINE
eight
nine
ten
with sed. That is, I want to replace the lines from /four/
(including) to /seven/
(including) with the single line NEW LINE
.
I can do that with
sed '/four/aNEW LINE
/four/,/seven/d' file.txt
But I am wondering if there is a simpler way, notably one without having to repeat a pattern (as I needed to with /four/
).
Edit As per fedorquis comment-question, this can also be in awk (although for "academic" purposes I'd be interested in sed solutions.)
Edit 2 Unfortunately, the input file suggests that there is a logical order of words in the input file (one followed by two followed by three etc). In my "real world" problem, this is not the case, however. I have no idea how many lines the file has, nor what is preceeded or followed by the lines four and seven. The onl thing I know is that there is a line four which is (not necessarily immediately) followed by a line seven. I am sorry for not stating this clearly when I asked the question, especially because fedorqui has put so much effort in his answer.
This might work for you (GNU sed & bash):
sed $'/^four/{:a;N;/^seven/McNEWLINE\nba}' file
这篇关于如何用sed中的单行替换两个模式之间的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!