Linux 如果行以另一个字符串开头,则替换文件中的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14262138/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:37:43  来源:igfitidea点击:

Replace string in a file if line starts with another string

linuxbashscriptingsed

提问by BlackBeret

How can I replace a string in a file if line starts with another string using sed?

如果行以使用 sed 的另一个字符串开头,如何替换文件中的字符串?

For example, replace this line:

例如,替换这一行:

connection = sqlite://keystone:[YOURPASSWORD]@[YOURIP]/keystone

With this line:

有了这条线:

connection = mysql://keystone:[email protected]/keystone

回答by anishsane

Answer:

回答:

sed '/^start_string/s/search_string/replace_string/'

Information at http://www.gnu.org/software/sed/manual/sed.html#Addresses

http://www.gnu.org/software/sed/manual/sed.html#Addresses 上的信息

回答by alinsoar

sed '/^string1/ { s,string2,string3, }' file

This will replace string2 with string3 on all the lines that start with string1.

这将在所有以 string1 开头的行上用 string3 替换 string2。

回答by kbekkouche

You can do simply this :

你可以简单地这样做:

sed -ri 's/sqlite/mysql/g' YOURFILE

回答by AstraSerg

If you want to change an entire line which starts with a pattern and ends with enything else, you can use command cdescriptionExample

如果要更改以模式开头并以其他任何内容结尾的整行,可以使用命令cdescriptionExample

sed -i '/^connection = sqlite/c\connection = mysql://keystone:[email protected]/keystone' your_file