考虑一下,我们有很多名称为的照片DSC_20170506_170809.JPEG
。为了重命名照片,使它们遵循模式Paris_20170506_170809.JPEG
,我编写了下面的脚本,效果很好。
for file in *.JPEG; do mv ${file} ${file/DSC/Paris}; done
我的问题是,我们如何使用while
循环而不是循环来编写此脚本for
?
在while
这里使用循环没有错。您只需要正确地做一下即可:
set -- *.jpeg
while (($#)); do
mv -- "${1}" "${1/DSC/Paris}"
shift
done
while
上面的循环与for
循环一样可靠(它将与任何文件名一起使用),而在许多情况下,后者是最适合使用的工具,而前者是一种有效的替代方法1,它有其用途(例如,以上可以一次处理三个文件,也可以仅处理一定数量的参数,等等)。
所有这些命令(set
,while..do..done
和shift
)都记录在外壳手动和他们的名字是不言自明的...
set -- *.jpeg
# set the positional arguments, i.e. whatever that *.jpeg glob expands to
while (($#)); do
# execute the 'do...' as long as the 'while condition' returns a zero exit status
# the condition here being (($#)) which is arithmetic evaluation - the return
# status is 0 if the arithmetic value of the expression is non-zero; since $#
# holds the number of positional parameters then 'while (($#)); do' means run the
# commands as long as there are positional parameters (i.e. file names)
mv -- "${1}" "${1/DSC/Paris}"
# this renames the current file in the list
shift
# this actually takes a parameter - if it's missing it defaults to '1' so it's
# the same as writing 'shift 1' - it effectively removes $1 (the first positional
# argument) from the list so $2 becomes $1, $3 becomes $2 and so on...
done
1:它不能替代文本处理工具,因此切勿使用while
循环来处理文本。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句