Search code examples
linuxbashshellopenwrt

Replace a substring by another one in bash


I have the following bash script

pass="kall"
cnumb="000000000000"

for (( i=0; i<${#pass}; i++))
do
    code=`printf '%03d' "'${pass:i:i+1}"` #generate the code ASCII of letter as string with 3 chars
    cnumb = .... #put the code ASCII of "k" in the first bloc of 3 chars , put the code ASCII of "a" in the second bloc of 3 chars, ...
done

As described in the code, I want to repace in each iteration in the loop a bloc of 3 chars in the cnumb by another bloc of 3 charachters. How to do it with bash

Is it possible to replace the sub string ${cnumb:i:i+3} by the code?


Solution

  • No need to put zeroes to cnumb. Also, use the %03d template for printf:

    #! /bin/bash
    pass="kall"
    cnumb=''
    
    for (( i=0; i<${#pass}; i++))
    do
        code=`printf '%03d' "'${pass:i:i+1}"` #generate the code ASCII of letter as string with 3 chars
        cnumb+=$code
    done
    echo "$cnumb"