2013-05-13 45 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