sed 替换不以 # 开头的匹配行

Fak*_*san 2 sed text-processing

我有一个名为“test-file”的文件。它只有以下两行(第一行带有# 符号,第二行内容相同但没有散列):

#contents of line
contents of line
Run Code Online (Sandbox Code Playgroud)

我想使用 sed 命令更新/替换第二行的内容。我知道它的简单语法,例如:

sed -i 's/.*contents of line.*/updated contents/' test-file
Run Code Online (Sandbox Code Playgroud)

但是上面的命令正在替换这两行,而我不想在前面用 # 符号更新第一行。

小智 6

您可以通过以下方式进行编辑:

sed -e '/^#/!s/.*/UPDATED_CONTENTS/' input-file.txt
Run Code Online (Sandbox Code Playgroud)

或者

sed -e '/^#/!c\
UPDATED_CONTENTS' input-file.txt
Run Code Online (Sandbox Code Playgroud)

这可以理解为:对于任何不以 a 开头的行#,将整行更改为指定的行。

如果您担心 octothorpe 前面可以有空格,请调整正则表达式,/^[[:blank:]]*#/同时保持其余部分原样。


αғs*_*нιη 5

尝试

sed 's/^[^#]*contents of line.*/updated contents/' test-file
Run Code Online (Sandbox Code Playgroud)

或者以行锚点开头^,并且您知道该行以 开头content ...,您可以这样做:

sed 's/^contents of line.*/updated contents/' test-file
Run Code Online (Sandbox Code Playgroud)

如果您知道要更新哪一行,则可以直接更改其地址行号,例如。

sed '2s/.*/updated content/' test-file
Run Code Online (Sandbox Code Playgroud)

-i当您对结果感到满意时添加。