linux - 用 bash 中的另一个子字符串替换一个子字符串

标签 linux bash shell openwrt

我有以下 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

如代码中所述,我想在循环中的每次迭代中将 cnumb 中的一个 3 个字符的 block 替换为另一个 3 个字符的 block 。如何用 bash 做到这一点

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

最佳答案

无需将零放入 cnumb。此外,为 printf 使用 %03d 模板:

#! /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"

关于linux - 用 bash 中的另一个子字符串替换一个子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16520140/

相关文章:

c++ - Linux 上的 PThreads 和多核 CPU

c - 段错误(核心已转储)。堆排序

Bash - SSH 多个命令,它们之间有延迟

linux - 得到选择。 -help 参数不起作用。

bash - 无法恢复我的登录 shell

c - 为什么一个程序的行为取决于它的 child 完成的顺序?

sql - sqlite3的最大表数

bash - 尝试将 mysqldump 到远程服务器上的 csv 时无法创建文件

linux - 同步shell脚本执行

linux - 与 grep 命令一起使用的 Shell 脚本变量