由於可能導致您的命令行超載,因此我不會執行for
循環。命令行的長度有限,如果你超載了它,它會簡單地刪除多餘的數據而不給你任何警告。它可能工作,如果你的查找返回100文件。它可能工作,如果它返回1000個文件,但它可能會失敗,如果你的查找返回1000個文件,你永遠不會知道。
處理此問題的最佳方法是將查找管道傳送到while讀取語句中作爲glenn jackman。
sed命令僅適用於標準輸入和文件,但不能在文件名,所以如果你想你的Munge時間的文件名,你就必須做這樣的事情:
$newname="$(echo $oldname | sed 's/old/new/')"
得到文件的新名稱。 $()
構造執行命令並將命令的結果放在STDOUT上。
所以,你的腳本就會是這個樣子:
find /home/devel/stuff/static/ -name "*.pdf" | while read $file
do
echo $file;
newfile="$(echo $file | sed -e 's/static/changethis/')"
newfile="$newfile.xml"
echo $newfile;
done
現在,因爲你重命名文件的目錄,你必須確保你做你的移動或複製之前所在的目錄:
find /home/devel/stuff/static/ -name "*.pdf" | while read $file
do
echo $file;
newfile="$(echo $file | sed -e 's/static/changethis/')"
newfile="$newfile.xml"
echo $newfile;
#Check for directory and create it if it doesn't exist
$dirname=$(dirname "$newfile")
if [ ! -d "$dirname" ]
then
mkdir -p "$dirname"
fi
#Directory now exists, so you can do the move
mv "$file" "$newfile"
done
請注意用引號來處理文件名中有空格的情況。
順便說一句,而不是做這樣的:
if [ ! -d "$dirname" ]
then
mkdir -p "$dirname"
fi
你可以這樣做:
[ -d "$dirname"] || mkdir -p "$dirname"
的||
手段,執行下面的命令只有在測試是不正確的。因此,如果[-d「$ dirname」]是錯誤語句(該目錄不存在),則運行mkdir
。
當您看到shell腳本時,這是一個相當常見的快捷方式。
沒有。我試圖獲取文件名,追加「.xml」並將其放在diff目錄中 – Mark
@Mark爲您更新了答案 –
@Mu Qiao:您的通配符擴展將會丟失靜態目錄中的任何.txt文件。 find命令不會。 –