shell格式化字符串
假如你有以下代码:
1 TEMP_SQL="SELECT count(uid) from ${TABLE_PREFIX}_%s;" 2 3 SUM=0 4 for((i=${MIN};i<${MAX};i++)); 5 do 6 echo "${TABLE_PREFIX}_${i}" 7 SQL= ??? 8 print ${SQL} 9 done
这个在我们写shell代码时是很常见的操作,上述代码的第7行,我希望以TEMP_SQL为模板将里面%s替换为for循环中i的值,该怎么操作呢?
答案:
1 TEMP_SQL="SELECT count(uid) from ${TABLE_PREFIX}_%s;" 2 3 SUM=0 4 for((i=${MIN};i<${MAX};i++)); 5 do 6 echo "${TABLE_PREFIX}_${i}" 7 SQL=$(printf "${TEMP_SQL}" ${i}) 8 print ${SQL} 9 done