2011-12-11 42 views
1

我試圖將指定目錄中的媒體和其他文件移動到另一個目錄,並且如果它不退出(文件將去)的位置,則創建另一個文件,並創建剩餘的目錄具有不同擴展名的文件將繼續。我的第一個問題是,我的腳本沒有創建一個新目錄,也沒有將文件移動到其他目錄,我可以使用哪些代碼將具有不同擴展名的文件移動到一個目錄?將文件移動到不同的目錄

這是我到目前爲止有,糾正我在哪裏,我錯了,並幫助修改我的腳本:

#!/bin/bash 
From=/home/katy/doc 
To=/home/katy/mo #directory where the media files will go 
WA=/home/katy/do # directory where the other files will go 
if [ ! -d "$To" ]; then 
    mkdir -p "$To" 
fi 
cd $From 
find path -type f -name"*.mp4" -exec mv {} $To \; 

回答

1

我會解決它有點像這樣:

#!/bin/bash 
From=/home/katy/doc 
To=/home/katy/mo # directory where the media files will go 
WA=/home/katy/do # directory where the other files will go 

cd "$From" 
find . -type f \ 
| while read file; do 
    dir="$(dirname "$file")" 
    base="$(basename "$file")" 
    if [[ "$file" =~ \.mp4$ ]]; then 
     target="$To" 
    else 
     target="$WA" 
    fi 
    mkdir -p "$target/$dir" 
    mv -i "$file" "$target/$dir/$base" 
    done 

注:

  • mkdir -p不會抱怨,如果該目錄已經存在,所以沒有必要以檢查。
  • 在所有文件名都包含空格的情況下放置雙引號。
  • 通過將find的輸出傳送到while循環中,您還可以避免被空格咬住,因爲read會一直讀到換行符。
  • 您可以根據喜好修改正則表達式,例如\.(mp3|mp4|wma|ogg)$
  • 如果您不知道,$(...)將運行給定的命令,並將其輸出保持在$(...)(稱爲命令替換)的位置。它幾乎與`...`相同,但略好(details)。
  • 爲了測試它,請在mv之前加echo。 (請注意,報價將消失在輸出中。)
1
cd $From 
find . -type f -name "*.mp4" -exec mv {} $To \; 
    ^^^ 

find $From -type f -name "*.mp4" -exec mv {} $To \; 
    ^^^^^ 
+0

即時嘗試,但它不工作錯誤顯示不能mv:沒有這樣的文件或目錄 – thequantumtheories

0
cd $From 
mv *.mp4 $To; 
mv * $WA; 
+0

它告訴我目標不是目錄 – thequantumtheories