在bourne shell中重命名文件

时间:2012-03-02 03:52:28

标签: scripting sh

我正在尝试编写 bourne-shell 脚本,该目录将目录作为参数并查找名为ixxx.a的图像并将其重命名为ixxx_a.img,其中“xxx表示分机号码”例如,图像文件名为i001.a,i002.a,i003.a ...) 在这里我尝试了什么

mv $1/f[0-9][0-9][0-9].a $1/f[0-9][0-9][0-9]_a.img

但它说DEST不是目录。 任何帮助将非常感激。感谢。

1 个答案:

答案 0 :(得分:1)

for i in $1/f[0-9][0-9][0-9].a; do
  mv $i ${i%.a}_a.img
done

但是,这不考虑文件/文件夹名称中的空格。在这种情况下,您必须使用while,以便每行获得一个文件名(请参阅下面的奖励)。可能有很多其他方式,包括rename

find $1 -maxdepth 1 -type f -name "f[0-9][0-9][0-9].a"|while read i; do
  mv "$i" "${i%.a}_a.img"
done

编辑:也许我应该解释一下我在那里做了什么。它被称为字符串替换,主要用例是变量var

# Get first two characters
${var:0:2}
# Remove shortest rear-anchored pattern - this one would give the directory name of a file, for example
${var%/*}
# Remove longest rear-anchored pattern
${var%%/*}
# Remove shortest front-anchored pattern - this  in particular removes a leading slash
${var#/}
# Remove longest front-anchored pattern - this would remove all but the base name of a file given its path
# Replace a by b
${var//a/b}
${var##*/}

有关详情,请参阅man页。