Blog Archive

Thursday, November 11, 2010

Howto: Linux Rename Multiple Files At a Shell Prompt

Linux批量重命名文件会涉及到改变一个字母、改变一些相连字母、改变某些位置的字母、在最前面加上某些字母、或者改变字母的大小写。完成这里五个方法基本上就会解决了Linux批量重命名的工作。

1、我想把它们的名字的第一个1个字母变为"q",其它的不变

[root@pps mailqueue]# for i in `ls`; do mv -f $i `echo $i | sed 's/^./q/'`; done

或者写个脚本,显得更加清晰:

for file in `ls`
do
newfile =`echo $i | sed 's/^./q/'`
 mv $file $newfile
done


2、修改前面5个字母为zhaozh

[root@pps mailqueue]# for i in `ls`; do mv -f $i `echo $i | sed 's/^...../zhaozh/'`; done

3、修改后面5个字母为snail

[root@pps mailqueue]# for i in `ls`; do mv -f $i `echo $i | sed 's/.....$/snail/'`; done

4、在前面添加 _hoho_

[root@pps mailqueue]# for i in `ls`; do mv -f $i `echo "_hoho_"$i`; done

5、所有的小写字母变大写字母

[root@pps mailqueue]# for i in `ls`; do mv -f $i `echo $i | tr a-z A-Z`; done

上面是五中完成有关Linux批量重命名方法。



====


Howto: Linux Rename Multiple Files At a Shell Prompt


How do I rename multiple files at a shell prompt under Linux or UNIX operating systems?

Renaming multiple files at a shell prompt is always considered as a black art by many UNIX gurus.

To be frank if you understand regex then it is not a black art anymore. A regular expression is a string that describes or matches a set of strings, according to certain syntax rules (see regex @ wikipedia for more information). Linux (and *BSD) comes with handy utility called rename. As a name suggest 'rename' renames the filenames supplied according to the rule specified (syntax):

rename "regex-rule" files
Rename command syntax

rename oldname newname *.files
For example rename all *.bak file as *.txt, enter:
$ rename .bak .txt *.bak

Examples: Linux Rename Multiple Files

Convert all mp3 filenames to more readable and usable format. Most of the time MP3 got multiple blank spaces, which may confuse many command line based Linux utilities and mp3 players

$ ls
Output:

06 - Gorillaz - Feel Good Inc.mp3
DDR - Kung- Fu Fighting (bus stop).mp3
AXEL CRAZYFROG.mp3
Remove all blank space with rename command:
$ rename "s/ *//g" *.mp3
$ ls

Output:

06-Gorillaz-FeelGoodInc.mp3
DDR-Kung-FuFighting(busstop).mp3
AXEL-CRAZYFROG.mp3
Linux Shell script to rename files

Before using the rename command I was using the following shell script to rename my mp3s:

#!/bin/bash
# To remove blank space
if [ $# -eq 0 ];
then
echo "Syntax: $(basename $0) file-name [command]"
exit 1
fi
FILES=$1
CMD=$2
for i in $FILES
do
# remove all blanks and store them OUT
OUT=$(echo $i | sed 's/ *//g')
if [ "$CMD" == "" ];
then
#just show file
echo $OUT
else
#else execute command such as mv or cp or rm
[ "$i" != "$OUT" ] && $($CMD "$i" "$OUT")
fi
done
To remove .jpg file extension, you write command as follows:

$ rename 's/\.jpg$//' *.jpg

To convert all uppercase filenames to lowercase:

$ rename 'y/A-Z/a-z/' *

Read the man page of rename command for more information:
man rename

No comments:

Post a Comment