2017-01-23 114 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?