2011-02-10 178 views
1

因此,我正在處理大量文件,並且希望將它們複製到一個目錄中,並將它們與一個附加的文件擴展名(例如「.copy」)一起存儲。C Shell腳本 - 追加到文件名的末尾

我真的不確定我可以用什麼命令將某些內容附加到文件末尾,是比我想的更簡單還是需要命令?

回答

2

您打算使用循環來做到這一點,還是試圖找到一個單行?如果你有一個文件$f,你可以只爲$f.copy附加版本。

+0

規劃一個循環,我將如何使用它來實際複製文件? – muttley91 2011-02-10 04:11:32

2
[email protected]:~/files> ls -1 
file1.txt 
file2.txt 
file3.txt 
[email protected]:~/files> ls -1 | xargs -I{} cp {} {}.copy 
[email protected]:~/files> ls -1 
file1.txt 
file1.txt.copy 
file2.txt 
file2.txt.copy 
file3.txt 
file3.txt.copy 

根據您的平臺,您可能需要稍微改變xargs的語法。我已經看到它使用-i{}-I{},但大寫變體似乎更常見。您當然可以在{}.copy文件名之前指定完整路徑名,以便文件最終位於不同的目錄中。

如果你需要做的不是一個班輪多一點,這裏還有這個:

ls -1 | { 
    while read _file; do 
     echo Copying $_file to $_file.copy 
     cp $_file $_file.copy 
    done 
} 

你可以把任何數量的行while循環。例如,您可以將同一個文件複製到十幾個不同的目標目錄或後綴。如果你只是粘貼它,你不需要製作一個腳本。結果看起來像這樣:

[email protected]:~/files> ls -1 
file1.txt 
file2.txt 
file3.txt 
[email protected]:~/files> ls -1 | { 
>  while read _file; do 
>   echo Copying $_file to $_file.copy 
>   cp $_file $_file.copy 
>  done 
> } 
Copying file1.txt to file1.txt.copy 
Copying file2.txt to file2.txt.copy 
Copying file3.txt to file3.txt.copy 
[email protected]:~/files> ls -1 
file1.txt 
file1.txt.copy 
file2.txt 
file2.txt.copy 
file3.txt 
file3.txt.copy 
[email protected]:~/files>