3

My original file:

nameserver 123.23.23.12
nameserver 10.0.1.13

I want to change it to:

nameserver 10.0.0.1
nameserver 10.0.1.13

command that I am using:

sed -i 's/nameserver*/nameserver 10.0.0.1/g' resolve.conf

Error that I am getting:

sed: -i may not be used with stdin

Also, when I use the below to test the output:

sed 's/nameserver*/nameserver 10.0.0.1/g' resolve.conf

I get:

nameserver 10.0.0.1 123.23.23.12

In second scenario, it is not replacing the complete line but just appending my replace text.

Any idea what I am doing wrong?

Thanks!

codeforester
  • 39,467
  • 16
  • 112
  • 140
Dadu
  • 373
  • 1
  • 3
  • 14

1 Answers1

2
sed 's/nameserver*/nameserver 10.0.0.1/g' resolve.conf

matches just nameserve followed by zero or more occurrences of r - essentially, just nameserver.

If you want to replace everything after nameserver, use this pattern:

sed 's/nameserver.*/nameserver 10.0.0.1/g' resolve.conf

But that would end up substituting both the lines in your resolv.conf. Why not just replace the IP address part?

To replace only the first occurrence, you can follow this post: How to use sed to replace only the first occurrence in a file?

To solve the issue with sed -i, pass a zero length option to the -i option so that it bypasses the creation of a backup file:

sed -i '' ...
Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140
  • Hi, IP address part is dynamic. That can be anything – Dadu Jan 31 '17 at 20:30
  • Tried: sed -i'' 's/nameserver.*/nameserver 10.0.0.1/g' resolve.conf. Still getting the same error. sed: -i may not be used with stdin – Dadu Jan 31 '17 at 20:34
  • Try `sed -i ''` - with a space after `-i`. I tried without that space on Mac OS and Ubuntu and it worked. What OS are you on? – codeforester Jan 31 '17 at 20:36
  • that worked!! Any clue on only replacing the first occurrence? – Dadu Jan 31 '17 at 20:41
  • If you have GNU `sed`, you can follow the steps from this post: http://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file – codeforester Jan 31 '17 at 20:43
  • Ok. I will try it out. – Dadu Jan 31 '17 at 20:44
  • 1
    BTW, even though the IP is dynamic doesn't prevent you from just finding and replacing it -- that's actually the whole point of regex; for example: sed 's/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/10.0.0.1/' – gregory Jan 31 '17 at 20:50