bash 替换文件中的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15161365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace line in files
提问by user2093552
How to replace the line in the file that begins with the text aaaI do not know where the line is.
如何替换文件中以文本开头aaa的行我不知道该行在哪里。
files.txt:
文件.txt:
sadasd_dsada = (aa,bb,cc)
aaa = (aa,bb,cc)
sadasd_dsada = (aa,bb,cc)
Replace:
代替:
aaa = (aa,bb,cc)
For:
为了:
aaa = (dd,ee,ff)
回答by Chris Seymour
The easiest way is to do a substitution with sed:
最简单的方法是使用sed以下方法进行替换:
$ sed 's/^aaa = (aa,bb,cc)$/aaa = (dd,ee,ff)/' file
sadasd_dsada = (aa,bb,cc)
aaa = (dd,ee,ff)
sadasd_dsada = (aa,bb,cc)
The characters ^and $match the start and the end of the line respectively in regexp meaning the substitution will only occur for whole line matches.
正则表达式中的字符^和分别$匹配行的开头和结尾,这意味着替换只会发生在整行匹配中。
Once you are happy with the changes use the -ioptions to save back to the file.
一旦您对更改感到满意,请使用-i选项将其保存回文件。
$ sed -i 's/^aaa = (aa,bb,cc)$/aaa = (dd,ee,ff)/' file
Edit:
编辑:
$ cat file
sadasd_dsada = (aa,bb,cc)
aaa = (aa,bb,cc)
aaa = foo
sadasd_dsada = (aa,bb,cc)
aaa = bar
$ sed 's/^aaa = .*/aaa = (dd,ee,ff)/' file
sadasd_dsada = (aa,bb,cc)
aaa = (dd,ee,ff)
aaa = (dd,ee,ff)
sadasd_dsada = (aa,bb,cc)
aaa = (dd,ee,ff)

