在 bourne shell 中重命名文件 [英] rename file in bourne shell

查看:50
本文介绍了在 bourne shell 中重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 bourne-shell 脚本,该脚本将目录作为参数并查找名为 ixxx.a 的图像并将它们重命名为 ixxx_a.img 其中xxx 表示示例图像文件将命名为 i001.a , i002.a ,i003.a ...)这是我试过的

I am trying to write a bourne-shell script that takes a directory as a parameter and look for images named ixxx.a and rename them to ixxx_a.img where "xxx means the extension number for exemple image files would be named i001.a , i002.a ,i003.a ...) here what I tried

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

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

but it says that the DEST is not a directory. Any help would be much appreciated. Thanks.

推荐答案

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

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

However, this does not consider blank spaces in the file/folder names. In this case you'd have to use while so you get one file name per line (see below for bonus). There are probably dozens of other ways, including 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:

Perhaps I should explain what I did there. It's called string substitution and the main use cases are these for a variable 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 页面.

For more see the man page.

这篇关于在 bourne shell 中重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆