shell脚本在文件名中间添加前导零
问题描述:
我有名称为“words_transfer1_morewords.txt”的文件。我希望确保“传输”之后的数字是五位数字,如“words_transfer00001_morewords.txt”中所示。我将如何使用ksh脚本来做到这一点?谢谢。shell脚本在文件名中间添加前导零
答
这将在任何Bourne类型/ POSIX壳工作,只要你话和morewords不包含数字:
file=words_transfer1_morewords.txt
prefix=${file%%[0-9]*} # words_transfer
suffix=${file##*[0-9]} # _morewords.txt
num=${file#$prefix} # 1_morewords.txt
num=${num%$suffix} # 1
file=$(printf "%s%05d%s" "$prefix" "$num" "$suffix")
echo "$file"
答
使用ksh
的正则表达式匹配操作,打破文件名分成不同的部分,格式化数字后又将它们重新组合在一起。
pre="[^[:digit:]]+" # What to match before the number
num="[[:digit:]]+" # The number to match
post=".*" # What to match after the number
[[ $file =~ ($pre)($num)($post) ]]
new_file=$(printf "%s%05d%s\n" "${.sh.match[@]:1:3}")
在成功匹配=~
,特殊的阵列参数.sh.match
包含元素0的全场比赛,并以起始元素中的每个捕获组1
嗯..你确定参数扩展/子串提取是POSIX? Bash - 是的,Bourne - ?? –
'%'和'#'都是POSIX(这与它们是否在Bourne中是正交的)。 'bash'扩展将使用'num = $ {file /%[0-9] *}'在一个操作中匹配和删除前缀。 – chepner
@ DavidC.Rankin是的,我确定。 POSIX在这里定义它:http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02我与The Opengroup合作:-) – Jens