Rename multiple files - linux/ubuntu

2019-06-07 09:19发布

I need to remove the "_1331045422" from image files in my directory.

for eg., my image file name looks like: message-16-error_1331045422.png

I actually ran a script which rename all image files this way. Also I have other files (image files with correct names, js files and css etc. which have correct names)

Please help me with a command to rename all image files with the "_1331045422" , without affecting others.

EDIT: I not only have .png files with the wrong filename. There are gifs and jpegs too.

4条回答
别忘想泡老子
2楼-- · 2019-06-07 09:38

Make a backup of your files before trying this!!

#!/bin/bash
for i in *.png; 
    do mv $i `echo $i | sed  "s/_[0-9]\+\.png^/\.png/"`
done
查看更多
家丑人穷心不美
3楼-- · 2019-06-07 09:38
#!/usr/bin/python
# message-16-error_1331045422.png --> message-16-error.png
# Usage: python foo.py dir_to_change
import os, sys
dir=sys.argv[1]
for file in os.listdir(dir):
    if not file.endswith('.png'):
        continue
    new, end = file.rsplit('_', 1)
    new=u'%s.png' % new
    file_old=os.path.join(dir, file)
    file_new=os.path.join(dir, new)
    os.rename(file_old, file_new)
查看更多
老娘就宠你
4楼-- · 2019-06-07 09:40

With rnm:

rnm -rs '/_\d+(\.)(png|gif|jpg|jpeg)/\1\2/' *

More examples here.

查看更多
forever°为你锁心
5楼-- · 2019-06-07 09:47

You can use rename command:

rename 's/_\d+(\..{1,3})/$1/g' *

You can change the range between {} if you have files with extension longer than three chars.

Be carefull that on some system the rename command is a bit different. Have a look here: https://superuser.com/questions/70217/is-there-a-linux-command-like-mv-but-with-regex

查看更多
登录 后发表回答