2013-05-13 40 views
0

由另一個替換一個子我有以下bash腳本在bash

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 

如在代碼所描述的,我想repace在循環每次迭代的3個字符的cnumb一個集團由另一3個charachters集團。如何用bash執行此操作

是否可以用代碼替換子字符串${cnumb:i:i+3}

回答

1

無需將零置入cnumb。此外,使用%03d模板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" 
+0

我想替換 – MOHAMED 2013-05-13 10:51:37

+0

@MOHAMED:然後使用'cnumb = $ {cnumb:0:我* 3} $代碼$ {cnumb:我* 3 + 3} ' – choroba 2013-05-13 10:58:31

+0

這就是我要找的。謝謝 – MOHAMED 2013-05-13 11:02:07