2016-02-03 187 views
0

我有幾百個文件需要排序到子目錄中。對於每個雙字母前綴,我想創建一個新目錄,並將所有以該前綴開頭的文件複製到該目錄中,並隨時刪除前綴。在BASH Shell腳本中創建文件和目錄

換句話說,00a00/a等等。

我有這樣的代碼:

cd try 
arr=$(ls) 

line=$(echo $arr | tr " " "\n") 
for x in $line 
do 
    if [ ! -d "$x" ] 
    then 
    s=${x:0:2} 
    if [ ! -d "$s" ] 
    then 
     mkdir "$s" 
    fi x=${x:-1:-1} 
    mv "$x" "$s" 
    fi done 

,但我得到這個持久錯誤:

arr - command not found. 

雖然我已經創建了200個文件成功,我無法創建新的目錄(如解釋,因此沒有文件)。

這裏是一個簡短的腳本來給文件名我有:

#!/bin/bash 
if [ ! -d "try" ] 
then 
    mkdir "try" 
fi 
cd try/ 
for x in {00..07} 
do 
    for y in {a..z} 
    do 
     touch $x$y 
    done 
done 
cd .. 
+2

的屏幕截圖是沒有用的,我們的。請粘貼代碼 –

+2

請不要發佈代碼圖片 - 將您的實際代碼粘貼到問題中。閱讀起來更容易,複製和測試更容易,搜索引擎更易於索引(意味着更多的人可以從您的問題中受益)。謝謝。 –

+1

從代碼快照我們只知道你喜歡玩反恐精英1.6 ...請發佈代碼,而不是快照:) –

回答

1
for i in [0-9][0-9]?* 
do 
    d=${i::2} 
    test -d "$d" || mkdir "$d" 
    mv "$i" "$d/${i:2}" 
done 

您可能希望set -e早些時候腳本提前硬失敗,如果mkdirmv失敗,或者你可能要推與其餘的文件 - 你的選擇。

我在一個新的,乾淨的目錄中測試了這個:

$ touch {00..20}{a..z}; for i in [0-9][0-9]?*; do d=${i::2}; test -d "$d" || mkdir "$d"; mv "$i" "$d/${i:2}"; done; ls -R 
.: 
00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 

./00: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./01: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./02: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./03: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./04: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./05: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./06: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./07: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./08: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./09: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./10: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./11: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./12: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./13: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./14: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./15: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./16: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./17: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./18: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./19: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

./20: 
a b c d e f g h i j k l m n o p q r s t u v w x y z 
+0

代碼工作正常,但在我的情況下,它構成了一個部分問題:它只移動00a,01a,002,.. 07a ..它應該也移動其他文件,因爲我創建了208個文件(208..007和a..z組合)..如何糾正這個錯誤.. –

+0

謝謝你的更清晰的解決方案.. –

相關問題