I want to replace a number at the end of a string by incrementing the number by one each time I run a specific sed line. the string looks like this:


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)/'

I would suggest perl instead of sed for this task:

perl -i -pe 's/(port=)(\d+)$/$1.($2+1)/e' filename

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=//') 
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.

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.