2017-01-23 113 views
2

我有成千上万名名为“DOCUMENT.PDF”的文件,我想根据路径中的数字标识符重命名它们。不幸的是,我似乎无法访问重命名命令。根据路径中的模式重命名文件

三个例子:

/000/000/002/605/950/ÐÐ-02605950-00001/DOCUMENT.PDF 
/000/000/002/591/945/ÐÐ-02591945-00002/DOCUMENT.PDF 
/000/000/002/573/780/ÐÐ-02573780-00002/DOCUMENT.PDF 

要改名为,在不改变它们的父目录:

2605950.pdf 
2591945.pdf 
2573780.pdf 
+0

*我似乎没有能够访问重命名命令*,你的意思是你没有执行'MV的能力'命令?如果原始文件位于'/ 000/000/002/...'中,那个文件夹是从哪里来的?当前目录或根目录?你想要结果文件去哪里? – lurker

+0

是的,我可以执行mv或cp。原始文件来自当前目录(不是根目录)。生成的文件可以转到当前目录。谢谢你的帮助! – Cinda

+0

'mv'是你如何在Unix中“重命名”一个文件。你是** m ** o ** v **它到一个不同的名字。 – lurker

回答

0

使用一个for循环,然后使用mv命令

for file in * 
do 
    num=$(awk -F "/" '{print $(NF-1)}' file.txt | cut -d "-" -f2); 
    mv "$file" "$num.pdf" 
done 
0

您可以在Bash 4.0+中使用globstar

cd _your_base_dir_ 
shopt -s globstar    
for file in **/DOCUMENT.PDF; do # loop picks only DOCUMENT.PDF files 
    # here, we assume that the serial number is extracted from the 7th component in the directory path - change it according to your need 
    # and we don't strip out the leading zero in the serial number 
    new_name=$(dirname "$file")/$(cut -f7 -d/ <<< "$file" | cut -f2 -d-).pdf 

    echo "Renaming $file to $new_name" 

    # mv "$file" "$new_name" # uncomment after verifying 
done 

看到这个相关的贴子,讨论了类似的问题:How to recursively traverse a directory tree and find only files?