我有一个需要一些更改的大文本文件。为此,我需要首先定位具有特定公共字符串的行,然后在此之后直接编辑该行。例如,如果我运行此grep
命令:
# grep -A1 important_string gianttextfile.txt
important_string
change_this
我想首先定位important_string
,然后修改change_this
为其他东西,在整个文档中多次。我不能只修改所有change_this
条目,因为其中许多条目需要保持原样,我只需要更改此特定字符串之后的那些条目。
实现这一目标的最佳方法是什么?
sed '/important_string/ {n;s/change_this/new_value/}'
笔记:
记住important_string
并被change_this
解析为正则表达式。
没有对s
执行的任何行进行测试,因此无法触发下一行。这意味着一个像这样的片段:important_string
s
…
foo # this line does not trigger s for the next line
important_string # this line triggers s for the next line
important_string # s is performed here
change_this # s in not performed here
…
不会改变。始终测试的变体important_string
是
sed ':start; /important_string/ {n;s/change_this/new_value/;b start}'
如果s
可以使important_string
出现或消失,那么您可能需要important_string
在替换前和/或替换后进行测试;或者不测试是否s
成功替换。这个答案并不涵盖所有这些情况。
s/…/…/g
需要时使用。
sed -i … file
需要时使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句