0

I am using tinydns and need to dynamicly change some ip in data file. I want to use bash script for it.

For example data file:

+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 script has two variables:

old="282.196.222.245"
new="127.0.0.1"

I expect this result:

+sub1.example.org:127.0.0.1:14400
+sub2.example.org:278.179.280.253:14400
+sub3.example.org:285.117.214.234:14400

What is the best way to replace old ip to new (using awk, sed or smth else)?

Jenny D
  • 27,780
  • 21
  • 75
  • 114
Andrei Nikolaev
  • 95
  • 1
  • 2
  • 5

3 Answers3

1

You can use sed:

sed -i "s/$old/$new/g" filename

Here you have simple test:

# 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>
fedorqui
  • 258
  • 4
  • 17
dave
  • 303
  • 3
  • 16
0
awk -v "old=$old" -v "new=$new" '$2 == old {$2 = new} {print}' filename > tempfile && mv tempfile filename

or

awk -v "old=$old" -v "new=$new" '$2 == old {$2 = new}1' filename > tempfile && mv tempfile filename
Dennis Williamson
  • 62,149
  • 16
  • 116
  • 151
0

I think it's cleaner to avoid trying to monkey-patch data; instead, generate your data from several files, one of which only contains the dynamic record(s).

Then, from bash, you can just echo "+sub3.example.org:285.117.214.234:14400" >data.dynamic; make or similar.

Example Makefile:

data.cdb : data 
    tinydns-data

data : data.static data.dynamic
    cat data.static data.dynamic >data
András Korn
  • 651
  • 5
  • 15