简体   繁体   English

如何使用regexp重命名linux shell中的文件?

[英]How to rename files in linux shell using regexp?

I have some files: 我有一些文件:

/var/www/media/0001/0001_123456_12.jpg
/var/www/media/0002/0002_123456_12.jpg
/var/www/media/0003/0003_123456_12.jpg

and I want to rename them to: 我想将它们重命名为:

/var/www/media/0001/0001_test.jpg
/var/www/media/0002/0002_test.jpg
/var/www/media/0003/0003_test.jpg

My idea was to find the first _ , remove the rest of the file until the . 我的想法是找到第一个_ ,删除文件的其余部分直到. then add test . 然后加上test

Any ideas? 有任何想法吗?

这是perl中的一个解决方案 ,允许您使用正则表达式。

find /var/www/media/ -name \*.jpg -exec sh -c '
  a=$(echo {} | sed s/_123456_/_/);
  [ "$a" != "{}" ] && mv "{}" "$a" '

You find all jpg files in the /var/www/media and run for each file the command: 您可以在/var/www/media找到所有jpg文件,并为每个文件运行命令:

a=$(echo {} | sed s/_123456_/_/)
[ "$a" != "{}" ] && mv "{}" "$a"

After this command, the a variable has rewritten name of the file inside: 在此命令之后, a变量重写了文件内部的名称:

a=$(echo {} | sed s/_123456_/_/)

The we compare the a variable and the realname ( {} ), and they are not equal the file must be renamed. 在我们比较a变量和真实姓名( {}他们是不相等的文件必须被重命名。

If you can install the mmv package, then these operations become easy. 如果您可以安装mmv包,那么这些操作就变得简单了。 With mmv , you can do what you want with: 使用mmv ,您可以随心所欲:

cd /var/www/media
mmv '*/*_123456_*.jpg' '#1/#2_test.jpg'

Here is the mmv manpage: http://manpages.ubuntu.com/manpages/lucid/man1/mln.1.html 这是mmv手册页: http ://manpages.ubuntu.com/manpages/lucid/man1/mln.1.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM