我有名称如“words_transfer1_morewords.txt”的文件。我想确保“转移”后的数字是五位数,如“words_transfer00001_morewords.txt”。我将如何使用 ksh 脚本执行此操作?谢谢。
问问题
239 次
2 回答
2
只要您的words和morewords不包含数字,这将在任何 Bourne 类型/POSIX shell 中工作:
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"
于 2015-11-06T20:48:55.313 回答
0
使用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 开始的每个捕获组。
于 2015-11-06T22:52:25.430 回答