linux - Increment my server-port in my Config file -


i want make bash script, increment server-port option in config file every time +1 if run script. config file looks this.

server-port=1000 server-online=true level-name=hapos type=xzc 

so example how needs work

# ./script.sh change port # cat config.txt 1001 ----------------- # ./script.sh change port # cat config.txt 1002 ----------------- # ./script.sh change port # cat config.txt 1003 

incrementing awk

let's start config file:

$ cat config.txt  server-port=1000 server-online=true level-name=hapos type=xzc 

we can increment port using awk:

$ awk -f= -v ofs== '$1 == "server-port"{$2++} 1' config.txt  server-port=1001 server-online=true level-name=hapos type=xzc 

the code works follows:

  • -f= sets field separator on input =.

  • -v ofs== sets field separator on output =.

  • $1 == "server-port"{$2++} tests see if first field server-port. if is, increments second field.

  • 1 awk's cryptic shorthand print-the-line.

changing in-place using modern (>=4.1.0) gnu awk

$ awk -i inplace -f= -v ofs== '$1 == "server-port"{$2++} 1' config.txt  $ cat config.txt  server-port=1001 server-online=true level-name=hapos type=xzc $ awk -i inplace -f= -v ofs== '$1 == "server-port"{$2++} 1' config.txt  $ cat config.txt  server-port=1002 server-online=true level-name=hapos type=xzc 

changing in-place other awks

$ awk -f= -v ofs== '$1 == "server-port"{$2++} 1' config.txt >tmp$$ && mv tmp$$ config.txt $ cat config.txt  server-port=1003 server-online=true level-name=hapos type=xzc 

alternative input file

suppose our file has dash above 1 had equal sign:

$ cat config.txt server-port-1000 server-online=true level-name-hapos type=xzc 

with gnu awk, can increment port number with:

awk -i inplace -f- -v ofs=- '/^server-port-/{$nf++} 1' config.txt  

this produces new file:

$ cat config.txt server-port-1001 server-online=true level-name-hapos type=xzc 

with awk other up-to-date gnu awk:

$ awk -f- -v ofs=- '/^server-port-/{$nf++} 1' config.txt >tmp$$ && mv tmp$$ config.txt $ cat config.txt server-port-1002 server-online=true level-name-hapos type=xzc 

notes on security , temporary files non-gnu solution

the updating in-place non-gnu awk requires creating temporary file. common put temporary files in /tmp security risk: other users can write directory making race conditions possible. danger can minimized using utility such mktemp makes hard-to-guess file names. still better solution put tmp file in directory user has write-access. can home directory.

in above, tmp file put in same directory config.txt file. directory secure because, config.txt is. if isn't, steps should taken.

for more information on issue, see greg's faq 062.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -