2012-10-09 115 views
2

我有36個子目錄名爲10,11,12相同的目錄,... 45和子目錄日誌Unix的複製從多個目錄中相同的文件到新目錄中,而重命名文件

在每個子目錄(目錄日誌除外)有相同的文件稱爲log.lammps

我想知道是否有一種方法,我可以從每個子目錄10-45複製每個log.lammps文件,並把它放在子目錄日誌,同時也添加它起源的目錄號到文件名的末尾

所以我在找一個鱈魚e從每個子目錄中逐一複製文件log.lammp,並且每次將文件複製到目錄日誌中時,文件名將從log.lammps更改爲log.lammps10(如果它來自子目錄10並且文件日誌從子目錄11的副本被複制到日誌其名稱更改爲log.lammps11等

任何幫助將不勝感激,因爲現在我只處理30-40個文件,在時間我將與數百個文件

+0

你願意接受這一答案之一,如果你的作品? –

回答

0

這很容易與貝殼腳本的魔力peasy。我假設你有bash可用。在包含這些子目錄的目錄中創建一個新文件;將其命名爲copy_logs.sh。將以下文本複製粘貼到其中:

#!/bin/bash 

# copy_logs.sh 

# Copies all files named log.lammps from all subdirectories of this 
# directory, except logs/, into subdirectory logs/, while appending the name 
# of the originating directory. For example, if this directory includes 
# subdirectories 1/, 2/, foo/, and logs/, and each of those directories 
# (except for logs/) contains a file named log.lammps, then after the 
# execution of this script, the new file log.lammps.1, log.lammps.2, and 
# log.lammps.foo will have been added to logs/. NOTE: any existing files 
# with those names in will be overwritten. 

DIRNAMES=$(find . -type d | grep -v logs | sed 's/\.//g' | sed 's/\///g' | sort) 

for dirname in $(echo $DIRNAMES) 
do 
    cp -f $dirname/foo.txt logs/foo$dirname 
    echo "Copied file $dirname/foo.txt to logs/foo.$dirname" 
done 

請參閱腳本的註釋以瞭解其功能。在保存文件後,您需要通過命令行命令chmod a+x copy_logs.sh來使其可執行。在此之後,您可以通過在命令行上鍵入./copy_logs.sh來執行它,而您的工作目錄是包含該腳本和子目錄的目錄。如果將該目錄添加到$ PATH變量中,則無論您的工作目錄是什麼,都可以使用命令copy_logs.sh

(我測試了GNU的bash v4.2.24腳本,所以它應該工作)

更多關於的bash shell腳本,看不到任何數量的書籍或互聯網網站;你可以從Advanced Bash-Scripting Guide開始。

+0

再次查看我的代碼,我發現包含字符串'logs'的所有目錄名將在變量'DIRNAMES'分配給時被刪除。爲了解決這個問題,該腳本可以適用於僅搜索名稱由數字組成的目錄。然而,我不會依賴目錄的命名約定,而只是將「logs」子目錄從目錄移開,以便我可以依賴所有具有某種類型的子目錄 - 在這種情況下,它將包含一個'log.lammps'文件。這很有道理。 –

0

東西沿着這條線應該工作:

for f in [0-9][0-9]/log.lammps; do 
    d=$(dirname ${f}) 
    b=$(basename ${f}) 
    cp ${f} logs/${b}.${d} 
done 
相關問題