从一系列文件夹中的文件中删除文件名的第二部分

时间:2017-02-07 14:42:13

标签: bash unix

我有一系列文件夹(大约100个),其中包含一组如下所示的文件:

Folder 1:
species_2136.dbf
species_2136.lyr
species_2136.prj
species_2136.sbn
species_2136.sbx
species_2136.shp
species_2136.shp.xml
species_2136.shx

Folder 2:
species_136524.dbf
species_136524.lyr
species_136524.prj
species_136524.sbn
species_136524.sbx
species_136524.shp
species_136524.shp.xml
species_136524.shx

我想要将所有内容命名为species.ext。如何从所有文件夹中的所有文件中删除_####看起来像这样?

Folder 1:
species.dbf
species.lyr
species.prj
species.sbn
species.sbx
species.shp
species.shp.xml
species.shx

Folder 2:
species.dbf
species.lyr
species.prj
species.sbn
species.sbx
species.shp
species.shp.xml
species.shx

3 个答案:

答案 0 :(得分:1)

使用Perl的重命名(独立命令):

rename -n 's/_[0-9]+//' "Folder "*/species*

如果一切正常,请删除选项-n

答案 1 :(得分:1)

bash parameter expansion

for file in ./{folder1,folder2}/*
do
    mv "$file" "${file%_*}"."${file#*.}"
done

(或)在一行中作为

for file in ./{folder1,folder2}/*; do mv "$file" "${file%_*}"."${file#*.}"; done

循环也可以完成,

for file in ./folder1/* ./folder2/*; do mv "$file" "${file%_*}"."${file#*.}"; done

答案 2 :(得分:0)

您的文件名

species_2136.dbf  
species_2136.lyr  
species_2136.prj  
species_2136.sbn  
species_2136.sbx  
species_2136.shp  
species_2136.shp.xml  
species_2136.shx  

rename命令非常简单易行。首先转到文件夹然后尝试:
rename -n 's/_.*?\./\./'

此处-n不执行任何操作,只是向您显示输出 棘手的部分是这个正则表达式:_.*?\.并且它匹配从_.的所有内容一次。并用一个点.代替它们就是它。

<强>证明

$ cat your-list-of-file | rename -n 's/_.*?\./\./'  
rename(species_2136.dbf, species.dbf)   
rename(species_2136.lyr, species.lyr)    
rename(species_2136.prj, species.prj)  
rename(species_2136.sbn, species.sbn)  
rename(species_2136.sbx, species.sbx)  
rename(species_2136.shp, species.shp) 
rename(species_2136.shp.xml, species.shp.xml)  
rename(species_2136.shx, species.shx)