0

I am writing a shell script for linux which takes argument as port no. inside file following is a line which needs to be updated:

define('NO_OF_PORTS',10);

I need to replace that 10 by the argument passed. But this should be dynamic, like next time I pass new port no it must get updated.

3 Answers 3

1

Using sed:

s="define('NO_OF_PORTS',10);"
n=25
sed "s/\('NO_OF_PORTS',\)[0-9]*/\1$n/" <<< "$s"
define('NO_OF_PORTS',25);

To change inline in the file use:

sed -i.bak "s/\('NO_OF_PORTS',\)[0-9]*/\1$n/" file
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry I think I'm the one who's making mistakes ><
Well I think I've made a mistake again.. There is a mistake: s='define('NO_OF_PORTS',10);' is not equivalent to s='define('\''NO_OF_PORTS'\'',10);' (or s="define('NO_OF_PORTS',10);"), while I think here it shall be the later ones but not the one you're using.
you eliminated single quotes around NO_OF_PORTS in your result.
0

You can use sed in the script to edit the file

sed -i s/NO_OF_PORTS\',[0-9]*/NO_OF_PORTS\',$1/ $2

Comments

0

1.txt has

define('NO_OF_PORTS',19)

shell script

#!/bin/sh
echo $1
sed -i -r '/NO_OF_PORTS/ s/'[0-9]+'/'$1'/g' 1.txt

run

linux:/home/test # ./replace_port.sh 78
linux:/home/test # cat 1.txt
define('NO_OF_PORTS',78)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.