[英]Creating files and directories in BASH Shell Scripting
我有幾百個文件要分類到子目錄中。 對於每個2個字母的前綴,我想創建一個新目錄,並將所有以該前綴開頭的文件復制到該目錄中,並隨即刪除該前綴。
換句話說, 00a
> 00/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 ..
for i in [0-9][0-9]?*
do
d=${i::2}
test -d "$d" || mkdir "$d"
mv "$i" "$d/${i:2}"
done
如果mkdir
或mv
失敗,則可能希望set -e
腳本中的set -e
早期硬故障,或者您可以繼續處理文件的其余部分-您的選擇。
我在一個干凈的新目錄中對此進行了測試:
$ 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.