在文件中指定行的开头插入字符

use*_*015 13 text-processing

我需要在文本文件中指定行的开头插入字符 (#)。

输入示例:

Hellow1
Hellow2
Hellow3
Run Code Online (Sandbox Code Playgroud)

期望输出

Hellow1
#Hellow2
Hellow3
Run Code Online (Sandbox Code Playgroud)

Kus*_*nda 12

#在带有单词的行上插入 a Hellow2,您可以这样使用sed

sed '/^Hellow2/ s/./#&/' input.txt >output.txt
Run Code Online (Sandbox Code Playgroud)

#在文本的第二行开头插入 a ,您可以这样使用sed

sed '2 s/./#&/' input.txt >output.txt
Run Code Online (Sandbox Code Playgroud)

&会由任何由模式匹配所取代。

我避免使用sed -i(就地编辑),因为我不知道sed您在使用什么,并且大多数实现的sed使用不兼容处理该标志的方式(请参阅如何使用 sed -i 实现可移植性(就地编辑) ?)。

相反,像上面那样进行替换,然后

mv output.txt input.txt
Run Code Online (Sandbox Code Playgroud)

如果你想用结果替换原始数据。这也让您有机会确保它正确出现。

等效的东西awk

awk '/^Hellow2/ { $0 = "#" $0 }; 1' input.txt >output.txt

awk 'NR == 2 { $0 = "#" $0 }; 1' input.txt >output.txt
Run Code Online (Sandbox Code Playgroud)


Bri*_*n C 5

你的问题不清楚。假设您要注释掉特定文本:

sed -i.bak 's/^\(Hellow2\)$/#\1/'
Run Code Online (Sandbox Code Playgroud)

这将对与字符串“Hellow2”完全匹配的任何行进行就地替换,并将它们替换为 # 后跟匹配的行。