2014-03-26 203 views
2

你好,我需要根據文件名來創建文件夾,這個文件夾中創建一個又一個,然後移動文件到這個第二個文件夾linux的bash腳本來創建文件夾和移動文件

例如:
my_file.jpg
創建文件夾my_file
創建文件夾圖片
移動my_file.jpg以圖片

我有這樣的劇本,但它僅適用於Windows,現在我使用Linux

for %%A in (*.jpg) do mkdir "%%~nA/picture" & move "%%A" "%%~nA/picture" 
pause 

對不起,如果我不精確,但英語不是我的母語。

回答

3
#!/usr/bin/env bash 

# Enable bash built-in extglob to ease file matching. 
shopt -s extglob 
# To deal with the case where nothing matches. (courtesy of mklement0) 
shopt -s nullglob 

# A pattern to match files with specific file extensions. 
# Example for matching additional file types. 
#match="*+(jpg|.png|.gif)" 
match="*+(.jpg)" 

# By default use the current working directory. 
src="${1:-.}" 
dest="${2:-/root/Desktop/My_pictures/}" 

# Pass an argument to this script to name the subdirectory 
# something other than picture. 
subdirectory="${3:-picture}" 

# For each file matched 
for file in "${src}"/$match 
do 
    # make a directory with the same name without file extension 
    # and a subdirectory. 
    targetdir="${dest}/$(basename "${file%.*}")/${subdirectory}" 
    # Remove echo command after the script outputs fit your use case. 
    echo mkdir -p "${targetdir}" 
    # Move the file to the subdirectory. 
    echo mv "$file" "${targetdir}" 
done 
+0

謝謝你,但我需要把目標文件夾放在哪裏,我的所有文件都在/ root/Desktop/My_pictures我試圖添加命令,在這個腳本應該看我的.jpg文件,但沒有運氣 – user3465420

+0

很好地完成;在這種情況下,'extglob'的一個簡單替代方法是使用'file in * .jpg * .png * .gif'(儘管您需要處理沒有任何匹配的情況,例如'shopt -s nullglob')。最好不要使用全大寫變量名稱以避免與環境變量衝突 - 請參閱http://stackoverflow.com/a/673940/45375 – mklement0

+0

您所有的jpg文件目前位於/ root/Desktop/My_pictures中?你想要他們在哪裏?你想傳遞參數給腳本還是在腳本中有目的地? – mjmcull

3

使用basename創建目錄名,mkdir創建該文件夾,並mv文件:

for file in *.jpg; do 
    folder=$(basename "$file" ".jpg")"/picture" 
    mkdir -p "$folder" && mv "$file" "$folder" 
done 
+0

難道你不是指'basename「$ file」「.jpg」'(路徑第一,然後後綴)? – mklement0

+0

@ mklement0謝謝。我無法相信我輸入了這個信息,並且它也被上傳了! – devnull

+0

:)這可能是由於~35k附帶的gravitas造成的。 – mklement0

1

嘗試以下操作:

for f in *.jpg; do 
    mkdir -p "${f%.jpg}/picture" 
    mv "$f" "${f%.jpg}/picture" 
done 

${f%.jpg}提取文件名前面的部分.jpg創建目錄。然後將文件移到那裏。

+0

這些值得放在''f''附近''quotes「' –

相關問題