bash 使用 shell 脚本替换文件中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8486967/
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 a string in file using shell script
提问by Pritom
Suppose my file a.conf is as following
假设我的文件 a.conf 如下
Include /1
Include /2
Include /3
I want to replace "Include /2" with a new line, I write the code in .sh file :
我想用新行替换“Include /2”,我在 .sh 文件中编写代码:
line="Include /2"
rep=""
sed -e "s/${line}/${rep}/g" /root/new_scripts/a.conf
But after running the sh file, It give me the following error
但是运行sh文件后,它给了我以下错误
sed: -e expression #1, char 14: unknown option to `s'
回答by luketorjussen
If you are using a newer version of sed you can use -ito read from and write to the same file. Using -iyou can specify a file extension so a backup will be made, incase something went wrong. Also you don't need to use the -eflag unless you are using multiple commands
如果您使用的是较新版本的 sed,您可以使用-i来读取和写入同一个文件。使用-i您可以指定文件扩展名,以便进行备份,以防出现问题。此外,除非您使用多个命令,否则您不需要使用-e标志
sed -i.bak "s/${line}/${rep}/g" /root/new_scripts/a.conf
I have just noticed that as the variables you are using are quoted strings you may want to use single quotes around your sed expression. Also your string contains a forward slash, to avoid any errors you can use a different delimiter in your sed command (the delimiter doesn't need to be a slash):
我刚刚注意到,由于您使用的变量是带引号的字符串,因此您可能希望在 sed 表达式周围使用单引号。此外,您的字符串包含一个正斜杠,为了避免任何错误,您可以在 sed 命令中使用不同的分隔符(分隔符不需要是斜杠):
sed -i.bak 's|${line}|${rep}|g' /root/new_scripts/a.conf
回答by Ivan Dimitrov
You have to write the changes to a new file and then, move the new file over the old one. Like this:
您必须将更改写入新文件,然后将新文件移到旧文件上。像这样:
line="Include 2"
rep=""
sed -e "s/${line}/${rep}/g" /root/new_scripts/a.conf > /root/new_scripts/a.conf-new
mv /root/new_scripts/a.conf-new /root/new_scripts/a.conf
回答by Eugene Yarmash
The redirection (> /root/new_scripts/a.conf
) wipes the contents of the file before sed
can see it.
重定向 ( > /root/new_scripts/a.conf
) 在sed
可以看到文件之前擦除文件的内容。
You need to pass the -i
option to sed
to edit the file in-place:
您需要将-i
选项传递sed
给就地编辑文件:
sed -i "s/${line}/${rep}/g" /root/new_scripts/a.conf
You can also ask sed to create a backup of the original file:
您还可以要求 sed 创建原始文件的备份:
sed -i.bak "s/${line}/${rep}/g" /root/new_scripts/a.conf