我正在使用tinydns,并需要dynamic地更改数据文件中的一些IP。 我想为它使用bash脚本。
例如数据文件:
+sub1.example.org:282.196.222.245:14400 +sub2.example.org:278.179.280.253:14400 +sub3.example.org:285.117.214.234:14400
bash脚本有两个variables:
old="282.196.222.245" new="127.0.0.1"
我期待这个结果:
+sub1.example.org:127.0.0.1:14400 +sub2.example.org:278.179.280.253:14400 +sub3.example.org:285.117.214.234:14400
什么是最好的方式来取代旧的IP新(使用awk,sed或smth其他)?
你可以使用sed:
sed -i "s/$old/$new/g" filename
在这里你有简单的testing:
# echo "+sub1.example.org:282.196.222.245:14400" >> filename # cat filename +sub1.example.org:282.196.222.245:14400 # old=282.196.222.245 # new=127.0.0.1 # sed -i "s/$old/$new/g" filename # cat filename +sub1.example.org:127.0.0.1:14400<br>
awk -v "old=$old" -v "new=$new" '$2 == old {$2 = new} {print}' filename > tempfile && mv tempfile filename
要么
awk -v "old=$old" -v "new=$new" '$2 == old {$2 = new}1' filename > tempfile && mv tempfile filename
我认为避免尝试对data更清晰; 而是从几个文件中生成data ,其中一个文件只包含dynamiclogging。
然后,从bash,你可以只echo "+sub3.example.org:285.117.214.234:14400" >data.dynamic; make echo "+sub3.example.org:285.117.214.234:14400" >data.dynamic; make或类似。
示例Makefile:
data.cdb : data tinydns-data data : data.static data.dynamic cat data.static data.dynamic >data