1

I need to find and replace either one or two numerical characters in strings in a file. The strings are IP addresses of the form:

10.xx.y.z 

Where xx can be one or two characters.

I want to replace the xx with the single character 0, so I have

10.0.y.z 

preserving the values of y and z.

The string may appear multiple times in the file. What is the sed invocation to do this?

migrated from serverfault.com Sep 10 '15 at 21:04

This question came from our site for system and network administrators.

2
n=[:digit:] o="[$n]\{1,3\}\."

sed -e"s/^/ /" \
    -e"s/\([^.$n]$o\)$o\($o${o%.})/\10.\2/g" \
    -e"s/.//" \
<in >out

It doesn't restrict the octets to 8bits, and it doesn't restrict the last octect to three digits, but it might be good enough.

If you want to edit the file in-place, the best way to do so (as opposed to using the often dangerous -i switch for perl or some seds) is to first get a temporary copy of the file, edit it, and then to write the edited, temporary copy back over your original. Most shells (including bash and zsh) will get you a secure, temporary file automatically when you request a here-document:

sed -e"#...script..." \
<<IN  >infile
$(cat <infile)
IN

The above will drop any trailing blank lines in infile if there are any, but there are numerous other answers on this site which demonstrate how to preserve those as well, if you require it. It also does not handle null bytes, which is a harder problem to solve without zsh.

  • This does exactly what I needed. Thank you very much for your help! – John Hupcey Sep 11 '15 at 13:53
  • You just have to be careful not to make "in" and "out" the same filename, otherwise you end up with a zero-length file. Not a good idea in any case. – John Hupcey Sep 11 '15 at 15:51
  • @JohnHupcey - yeah, don't do that. See the edit. – mikeserv Sep 11 '15 at 16:03
  • Unfortunate side effect is that it not only changes 10.xx.y.z strings, but also changes netmasks like 255.255.255.0 to 255.0.255.0. Not good! I thought it was restricting edits to strings that began with "10." but evidently not. – John Hupcey Nov 4 '15 at 19:18
  • @JohnHupcey - i was pretty clear about that in the answer. – mikeserv Nov 4 '15 at 21:11
0

Assuming (as specified) that file is composed of string and string are IP

with 1 IP per line

sed 's/.[^.]*/0/' YourFile

With several IP per line

sed 's/\([0-9]\{1,3\}[.]\)[^.]*\(\([.][[:alnum:]]\{1,\}\)\{2\}\)/\1.0\2/g' YourFile
0

This works:

o="[[:digit:]]\{1,3\}"  
sed  -e"s/10\.$o\.\($o\.$o\)/10.0.\1/g" <input.txt >output.txt

Modifies 10.X.y.z to 10.0.y.z in any position in a file, even multiple times on the same line. Doesn't mess with arbitrary WWW.x.y.z strings at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.