Swapnil Walivkar
Swapnil Walivkar

Reputation: 295

Shell script to replace string dynamically

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.

Upvotes: 0

Views: 2096

Answers (3)

oyss
oyss

Reputation: 692

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)

Upvotes: 0

anubhava
anubhava

Reputation: 785146

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

Upvotes: 1

jhnesk
jhnesk

Reputation: 29

You can use sed in the script to edit the file

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

Upvotes: 0

Related Questions