2014-10-09 110 views
0

我正在運行名爲filename_to_dir.sh的腳本,該腳本在while循環內採用參數-s。該參數是一個.txt文件名。我使用while循環對它在特定目錄中找到的每個文件執行腳本,然後使用格式化的文件名創建子目錄。但是在創建任何目錄之前,文件名將被格式化,並刪除空白和其他一些東西以避免在將其提供給filename_to_dir.sh時出錯。唯一的問題是目錄被格式化的名稱,但文本文件名保持不變。如何根據格式化的文件名創建一個目錄?根據文本文件名創建目錄名稱

當前結果:

|-- text_files 
| |-- this_is_new-1 
| |-- test_11-today 
| |-- hi_hi-Bye 
| |-- this is new - 1.txt 
| |-- test 11 - today.txt 
| |-- hi HI - Bye.txt 

期望的結果:

|-- text_files 
| |-- this_is_new-1 
| |-- test_11-today 
| |-- hi_hi-Bye 
| |-- this_is_new-1.txt 
| |-- test_11-today.txt 
| |-- hi_hi-Bye.txt 

兩個方法我已經嘗試過了:

while read -r file; do 
    new_file=$(echo "$file" | sed -re 's/^([^-]*)-\s*([^\.]*)/\L\1\E-\2/' -e 's/ /_/g' -e 's/_-/-/g') 
    if [ "$file" != "$new_file" ]; then 
     echo mv "$file" "$new_file" 
     file_split.sh -s $file 
    fi 
done < <(find $FILE_PATH -type f -name '*.txt') 

//Using find but i loose a way to check if file has been renamed already 
while read -r file; do 
    file_split.sh -s $file 
done < <(find $FILE_PATH -type f -exec bash -c 'echo "mv \"$1\" \"$(echo "$1" | sed -re '\''s/^([^-]*)-\s*([^\.]*)/\L\1\E-\2/'\'' -e '\''s/ /_/g'\'' -e '\''s/_-/-/g'\'')\""' - {} \;) 
+0

爲什麼要在循環中運行sudo? – 2014-10-09 02:51:05

+0

@JohnZwinck糾正了這一點。 – 2014-10-09 02:53:00

回答

1

我認爲你應該改變echo mv "$file" "$new_file"mv "$file" "$new_file"