【问题标题】:batch rename files in ubuntu在ubuntu中批量重命名文件
【发布时间】:2014-03-07 15:14:55
【问题描述】:
我需要一些命令行功能。
我有一堆文件,以 4 个数字开头,然后是破折号,然后是各种字母,然后是扩展名,例如。
0851_blahblah_p.dbf
0754_asdf_l.dbf
我想要的是将四个数字移动到文件名的末尾(保持扩展名完好)并删除下划线。因此上面的例子将被重命名:
blahblah_p0851.dbf
asdf_l0754.dbf
感谢所有帮助。
我正在运行 ubuntu。
谢谢DJ
【问题讨论】:
标签:
linux
command-line
sed
【解决方案1】:
这是纯bash的解决方案:
for file in *.dbf; do
ext=${file##*.};num=${file%%_*};name=${file%.*};name=${name#*_}
mv $file $name$num"."$ext;
done
用 cmets 分解:
for file in *.dbf
do
ext=${file##*.} # Capture the extension
num=${file%%_*} # Capture the number
name=${file%.*} # Step 1: Capture the name
name=${name#*_} # Step 2: Capture the name
mv "$file" "$name$num.$ext" # move the files to new name
done
【解决方案2】:
您可以使用rename 命令:
rename 's/([0-9]{4})_([[:alpha:]]*)_.*.dbf/$2_$1.dbf/' *
【解决方案3】:
你也可以使用 sed
$sed -r 's/([^_]+)_([^.]+)/\2\1/g'
使用这种方式,给定的名称会根据您的要求进行拆分和修改。
(或)
使用此脚本并将文件名作为参数传递,它将根据要求移动文件名。
#!/bin/sh
if [ $# -ne 1 ] ; then
echo "Usage : <sh filename> <arguments>"
exit ;
fi
for file in $*
do
mv $file `echo $file | sed -r 's/([^_]+)_([^.]+)/\2\1/g' `
done