如何更改包含模式的行的第一次出现? [英] How to change the first occurrence of a line containing a pattern?

查看:32
本文介绍了如何更改包含模式的行的第一次出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到第一次出现模式的行,然后我需要用一个全新的行替换整行.

I need to find the line with first occurrence of a pattern, then I need to replace the whole line with a completely new one.

我发现这个命令替换了模式的第一次出现,但不是整行:

I found this command that replaces the first occurrence of a pattern, but not the whole line:

sed -e "0,/something/ s//other-thing/" <in.txt >out.txt

如果 in.txt 是

If in.txt is

one two three
four something 
five six
something seven

结果我进入了out.txt:

As a result I get in out.txt:

one two three
four other-thing
five six
something seven

然而,当我尝试修改这段代码以替换整行时,如下:

However, when I try to modify this code to replace the whole line, as follows:

sed -e "0,/something/ c\COMPLETE NEW LINE" <in.txt >out.txt

这是我在 out.txt 中得到的:

This is what I get in out.txt:

COMPLETE NEW LINE
five six
something seven

你知道为什么第一行丢失了吗?

Do you have any idea why the first line is lost?

推荐答案

c\ 命令删除所有行,包括第一个匹配地址到第二个匹配地址, 当与 2 个地址一起使用时,并在匹配第二个地址时打印出 c\ 后面指定的文本.如果输入中没有与第二个地址匹配的行,它只会删除第一个匹配地址到最后一行之间的所有行(包括).由于您只想替换一行,因此不应在地址范围内使用 c\ 命令.在正常使用中,c\ 后面紧跟一个换行符.0,/regexp/ 地址范围是 GNU sed 扩展,它也会尝试匹配第一行输入中的 regexp,即在这方面与 1,/regexp/ 不同.因此,GNU sed 中的正确命令可能是

The c\ command deletes all lines between and inclusive the first matching address through the second matching address, when used with 2 addresses, and prints out the text specified following the c\ upon matching the second address. If there is no line matching the second address in the input, it just deletes all lines (inclusively) between the first matching address through the last line. Since you want to replace one line only, you shouldn't use the c\ command on an address range. The c\ is immediately followed by a new-line character in normal usage. The 0,/regexp/ address range is a GNU sed extension, which will try to match regexp in the first input line too, which is different from 1,/regexp/ in that aspect. So, the correct command in GNU sed could be

sed '0,/something/{/something/c\
COMPLETE NEW LINE
}' < in.txt

或者像 Sundeep 指出的那样简化

or simplified as pointed out by Sundeep

sed '0,/something/{//c\
COMPLETE NEW LINE
}' < in.txt

或单线,

sed -e '0,/something/{//cCOMPLETE NEW LINE' -e '}' < in.txt

如果不需要文字换行符.

if a literal new-line character is not desirable.

这个单线也像potong所指出的那样工作:

This one-liner also works as pointed out by potong:

sed '0,/something/!b;//cCOMPLETE NEW LINE' in.txt

这篇关于如何更改包含模式的行的第一次出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆