5

I want to change a number at the end of a string by incrementing that number by one each time I run a specific sed line.

The string looks like this:

server-port=25555

I was thinking I could run something like this sed line to do it, but it doesn't work.

sed -i 's/port=[0-9]{5}/int(&+1)/'
AdminBee
  • 21,637
  • 21
  • 47
  • 71
Connor Law
  • 51
  • 1
  • 2
  • 2
    checkout http://unix.stackexchange.com/questions/36949/addition-with-sed – Vikyboss Apr 13 '16 at 19:07
  • you tagged ubuntu, which may have gnu sed, in which case you can use this: http://unix.stackexchange.com/q/231596/117549 -- otherwise, "standard" sed doesn't have math functions built-in. Most people turn to perl for this (see: http://unix.stackexchange.com/q/116372/117549) – Jeff Schaller Apr 13 '16 at 20:32
  • If any of the existing answers solves your problem, please consider accepting it via the checkmark. Thank you! – Jeff Schaller Apr 23 '17 at 12:55

3 Answers3

9

I would suggest perl instead of sed for this task:

perl -i -pe 's/(port=)(\d+)$/$1.($2+1)/e' filename
Guido
  • 4,014
  • 13
  • 22
1
echo "server-port=25555" | sed  -E 's/(.*-port=)([0-9]+)/echo "\1$((\2+1))"/e' 
Walter A
  • 694
  • 4
  • 11
0

If you don't mind a multi-liner, you can work around it using sed and shell math with:

# or however else you're getting the server-port section
num=$(echo server-port=25555 | sed 's/server-port=//') 
v=$((v+1))
sed -i "s/server-port=25555/server-port=$v/" your-file-here

Note the double-quotes around the sed expression; that's so that $v can be interpreted before sed sees it. In this particular case, you could leave the sed expression unquoted, since there's nothing else in there for the shell to (mis)-interpret.

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250