问题
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