Bash how to replace nth character in a string

Viewed 58

I have a string with in a file:

"1.0.0.0.5";

I would like to replace 5 with 6 so the output should look like

"1.0.0.0.6";

could you please help me in this to achieve the output as above in bash

3 Answers

It seems to me that what you really want to do is increment the 5th dot-delimited field in that line.

line='"1.0.0.0.5";'
if [[ $line =~ \"([^\"]+) ]]; then 
    IFS="." read -ra fields <<< "${BASH_REMATCH[1]}"
    ((++fields[-1]))
    (
        IFS="."
        printf '"%s";\n' "${fields[*]}"
    )
fi
"1.0.0.0.6";

bash doesn't have an operator for assigning to a string index. So you'll need to concatenate the portions before and after the index you want to replace.

s=1.0.0.0.5
s=${s:0:8}6${s:9:}

${s:0:8} means the first 8 characters, and ${s:9:} means all the characters starting from index 9. So this replaces the character at index 8.

You can use a Bash regex:

s="1.0.0.0.5"

replacement="6"

[[ $s =~ ^(.*\.)[^.]*$ ]]

echo "${BASH_REMATCH[1]}$replacement"

Prints:

1.0.0.0.6
Related