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
  • 71,145
  • 9
  • 121
  • 139
tso
  • 167
  • 3
  • 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
  • 7,889
  • 15
  • 41
  • 65
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
  • 940
  • 5
  • 11