replace a string by variable in a file using bash script
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.txtSample input:
project web0Sample output:
project web1 8 3 Answers
AWK can search and replace text as well, so there is no need to use grep or sed. The code bellow extracts substring from second column (webN), increments N, and substitutes second field with webN+1
$ cat testInput.txt
project web0
other
project web1
$ awk '/web/{ num=substr($2,4)+1;$2="web"num };1' testInput.txt
project web1
other
project web2This 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 using mv fileName.txt oldFile.txt
Using Perl:
perl -pe 's/\bweb\K[0-9]+\b/$&+1/ge' fileTo edit the file in place, add the -i option:
perl -i -pe 's/\bweb\K[0-9]+\b/$&+1/ge' file-p: causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed:LINE: while (<>) { ... # your program goes here } continue { print or die "-p destination: $!\n"; }-e: may be used to enter one line of program.s/\bweb\K[0-9]+\b/$&+1/ge: matches anywebstring preceded by a word boundary, discards the match and matches one or more digits followed by a word boundary, replacing the match with the equivalent number increased by 1.
% cat file
project web0
project web1
project web2
% perl -pe 's/\bweb\K[0-9]+\b/$&+1/ge' file
project web1
project web2
project web3 1 Thanks guys, I tried this code and that worked fine for me,
#!/bin/bash
DPATH="/root/test.txt"
k=$(grep 'web' $DPATH | awk '{print $2}') # web ends by a number#
i=$(grep 'web' $DPATH | awk '{print $2}'| cut -c3)
m=$((i+1))
n="web$m"
sed -i -e 's/'"$k"'/'"$n"'/g' $DPATH