How to replace a word through a variable after searching?

可紊 提交于 2020-01-06 06:48:11

问题


I have a problem like this. In a text file(which is called sampleText.txt) has the web url like this,

webURL = "localhost.com"; 

I want to change this value using a bash script. But I tried with this my script, bt it did not worked, here is my script,


#!/bin/bash 

URL=$(awk -F\" '/^webURL/{print $2}' sampleText.txt)

echo $URL 


if [ "$URL" != "www.google.com" ]; then

shopt -s globstar for file in sampleText.txt 

do

   sed -i.bak 's/$URL/www.google.com/g' $file 

done 

fi 

I hope you will help me. Any help would be greatly appreciated, Thankx... :)


回答1:


If I understand your intent, you want to change every URL in lines which begin with webURL = to "www.google.com"? If so, you simply

$ sed -i.bak -r '/^webURL/{s/"[^"]+"/"www.google.com"/}' sampleText.txt

If you have a mixture of single and double quotes, you can use

$ sed -i.bak -r "/^webURL/{s/['\"][^'\"]+[\"']/\"www.google.com\"/}"

which will normalise to double quotes.




回答2:


sed -i "s|\("webURL" *= *\).*|\1www.google.com|" sampleText.txt



回答3:


the script can be update to:

#!/bin/bash 

url="www.google.com"
sed -i.bak "/^webURL/{s@\"[^\"]*\"@\"$url\"@}" sampleText.txt


来源:https://stackoverflow.com/questions/23106168/how-to-replace-a-word-through-a-variable-after-searching

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!