Linux 在 shell 脚本中查找和替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10856749/
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
Find and replace in shell scripting
提问by Amanada Smith
Is it possible to search in a file using shell and then replace a value? When I install a service I would like to be able to search out a variable in a config file and then replace/insert my own settings in that value.
是否可以使用 shell 在文件中搜索然后替换一个值?当我安装服务时,我希望能够在配置文件中搜索出一个变量,然后在该值中替换/插入我自己的设置。
采纳答案by Oleksandr Kravchuk
Sure, you can do this using sed or awk. sed example:
当然,您可以使用 sed 或 awk 来执行此操作。sed 示例:
sed -i 's/Andrew/James/g' /home/oleksandr/names.txt
回答by Paulo Scardine
Generally a tool like awk or sed are used for this.
通常像 awk 或 sed 这样的工具用于此目的。
$ sed -i 's/ugly/beautiful/g' /home/bruno/old-friends/sue.txt
回答by Flashpix
You can use sed to do this:
您可以使用 sed 来执行此操作:
sed -i 's/toreplace/yoursetting/' configfile
sed is probably available on every unix like system out there. If you want to replace more than one occurence you can add a g to the s-command:
sed 可能在每个类似 Unix 的系统上都可用。如果要替换多个出现,可以将 ag 添加到 s 命令:
sed -i 's/toreplace/yoursetting/g' configfile
Be careful since this can completely destroy your configfile if you don't specify your toreplace-value correctly. sed also supports regular expressions in searching and replacing.
请小心,因为如果您没有正确指定 toreplace-value,这可能会完全破坏您的配置文件。sed 还支持搜索和替换中的正则表达式。
回答by embedded.kyle
sed -i 's/variable/replacement/g' *.conf
回答by Vidul
Look at the UNIX power toolsawk, sed, grepand in-place edit of fileswith Perl.
回答by octopusgrabbus
You can use sed to perform search/replace. I usually do this from a bash shell script, and move the original file containing values to be substituted to a new name, and run sed writing the output to my original file name like this:
您可以使用 sed 执行搜索/替换。我通常从 bash shell 脚本执行此操作,并将包含要替换为新名称的值的原始文件移动,然后运行 sed 将输出写入我的原始文件名,如下所示:
#!/bin/bash
mv myfile.txt myfile.txt.in
sed -e 's/PatternToBeReplaced/Replacement/g' myfile.txt.in > myfile.txt.
If you don't specify an output, the replacement will go to stdout.
如果您不指定输出,则替换将转到标准输出。
回答by user68775
filepath="/var/start/system/dir1"
searchstring="test"
replacestring="test01"
i=0;
for file in $(grep -l -R $searchstring $filepath)
do
cp $file $file.bak
sed -e "s/$searchstring/$replacestring/ig" $file > tempfile.tmp
mv tempfile.tmp $file
let i++;
echo "Modified: " $file
done