Shell Geek:一次重命名多个文件

Let’s say you have a directory with hundreds of files with the wrong file names, and you’d like to replace every filename containing test with prod. (this is a contrived example). We can easily do this with the “for” command in bash, combined with a little bit of bash goodness. Today we’ll learn how to replace text in a variable in a for loop.

假设您的目录中包含数百个文件名不正确的文件,并且您希望将每个包含test的文件名替换为prod 。 (这是一个人为的示例)。 我们可以轻松地使用bash中的“ for”命令以及一点点bash优点来完成此操作。 今天,我们将学习如何在for循环中替换变量中的文本。

The “for” command works like this:

“ for”命令的工作方式如下:

for var in <files>;do <command> $var;done

用于<文件>中的var;执行<命令> $ var;完成

You can replace <files> with any file match pattern, such as * or *.txt, and you can replace <command> with any linux command. The command will be run in sequence on each of the files matched by the file match pattern.

您可以将<files>替换为任何文件匹配模式,例如*或* .txt,并且可以将<command>替换为任何linux命令。 该命令将在文件匹配模式匹配的每个文件上依次运行。

This is where the bash variable handling makes it even more interesting. Instead of just doing something like “mv $var”, we can replace text in the filename using this syntax:

这是bash变量处理使其变得更加有趣的地方。 除了使用“ mv $ var”之类的方法,我们还可以使用以下语法替换文件名中的文本:

${var/originaltext/replacetext}

$ {var / originaltext / replacetext}

So now, if we run this command on our directory:

所以现在,如果我们在目录中运行以下命令:

for f in *;do mv $f ${f/test/prod};done

对于*中的f;执行mv $ f $ {f / test / prod};完成

For each file matched by *, bash will execute a command similar to this:

对于每个*匹配的文件,bash将执行类似于以下命令:

mv test.config prod.config

mv test.config prod.config

I’ve found that knowledge of the shell is invaluable when administering servers or just for managing your file collection, and has saved me hours of what would have otherwise been manual work.

我发现,在管理服务器或仅用于管理文件收集时,对外壳的了解非常宝贵,并且为我节省了原本应该是手工工作的时间。

And yes, I realize there are a number of tools that can accomplish renaming of multiple files.

是的,我意识到有许多工具可以完成多个文件的重命名。

翻译自: https://www.howtogeek.com/howto/ubuntu/shell-geek-rename-multiple-files-at-once/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值