find a string in text file and replace the line with variable

时间:2019-01-09 21:55:24

标签: unix sed

I have variable ips: "10.34.34.34, 10.42.42.42, 10.55.55.55"

and cat ips.txt ips: ""

I want to replace the line in my file ips.txt with variable. With sed my ips.txt should look like cat ips.tx

sed "s/.*ips*/$varaible/g" ips.txt

I've tried sed "s/.*ips*/$varaible/g" ips.txt; it did print output, but not replace the line in my file.

How would I replace the line in my file?

sed "s/.*ips*/$varaible/g" ips.txt

cat ips.txt should look like ips: "10.34.34.34, 10.42.42.42, 10.55.55.55"

2 个答案:

答案 0 :(得分:0)

sed normally outputs to stdout, which defaults to the screen. You can redirect it to a new file like this:

sed "s/.ips/$var/g" ips.txt > new_ips.txt

If you're feeling brave, you can have the edits occur in place, and change the original file by using the -i switch:

sed -i "s/.ips/$var/g" ips.txt

Note, this can be dangerous. If you make a mistake, the original content of the file is gone.

答案 1 :(得分:0)

  

如果两次运行此命令,我将两次获得ips.txt中列出的ips ...

只需指定搜索模式,以便仅匹配替换之前的文本,例如e。 g。:

var='ips: "10.34.34.34, 10.42.42.42, 10.55.55.55"'

sed -i "s/ips: \"\"/$var/" ips.txt   # match only with empty quote ("")