2

I have a problem. I want to write an IP into a file with sed

newsource=1.2.3.4/24
sed -i 's/.*#source*/&\n'"$newsource"'/' file

$newsource is an IP, which CAN contain a net-mask /24 or not. Right now the sed writes the full IP but not the /24. How can I change that?

Inian
  • 80,270
  • 14
  • 142
  • 161
tso
  • 187
  • 4
  • 13

2 Answers2

2

This is because you must either escape your /, or change the sed separator to something else:

escape: \/

newsource=1.2.3.4\/24
sed -i 's/.*#source*/&\n'"$newsource"'/' file

or

change sed separator to ~

newsource=1.2.3.4/24
sed -i 's~.*#source*~&\n'"$newsource"'~' file

Share and enjoy.

Community
  • 1
  • 1
J. Chomel
  • 8,193
  • 15
  • 41
  • 69
2

Try:

sed -i 's|.*#source*|&\n'"${newsource}"'|' file

You could use \ to escape the / but since the path is stored in a variable it's probably easier to use a different separator.

Nunchy
  • 948
  • 5
  • 11