through bash script, I am trying to find a value-number- from a text in a file, then make a new variable then replace it with a string in that file
for example. in a file in /root/test.txt , i have a string web1
i need to cut the number "1", and increase it by 1 so it will be 2
then replace web1 by web2
that is what i did so far
any idea how to make it works ?
#!/bin/bash
m=grep 'web' /root/test.txt | awk '{print $2}'
i= $m | cut -c3
i=i+1
n='web$i'
$ sed -i 's/$m/$n/g' /root/test.txt
Sample input:
project web0
Sample output:
project web1
Best Answer
AWK can search and replace text as well, so there is no need to use
grep
orsed
. The code bellow extracts substring from second column (webN
), incrementsN
, and substitutes second field withwebN+1
This will print edited file on screen. You can save that to another file like so
awk [rest of code here] > fileName.txt
and replace original with new usingmv fileName.txt oldFile.txt