How do I create a script in a command prompt (or shell script in a bash) to divide files depending on a number, say X, and put into individual folder.
Example: I have 10 files and the number X is 4 (I can set it inside the script). So, the system will create 3 folders (1st folder contain 4 files, 2nd folder contain 4 files and the last folder will contain the remaining 2 files) after running the sc开发者_StackOverflowript.
Regarding about the divide of the files. It can be either go by the date or the filename.
Example: Suppose the 10 files above is a.txt, aa.txt, b.txt, cd.txt, ef.txt, g.txt, h.txt, iii.txt, j.txt and zzz.txt. After running the script, it will create the 3 folders such that the 1st folder contain a.txt, aa.txt, b.txt, cd.txt, the 2nd folder contains ef.txt, g.txt, h.txt, iii.txt and the last folder will contain the remaining files - j.txt and zzz.txt
Based on your description, an awk one liner could achieve your goal.
check the example below, you can change "4" in xargs -n parameter with your X:
kent$ l
total 0
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 01.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 02.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 03.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 04.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 05.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 06.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 07.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 08.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 09.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 10.txt
kent$ ls|xargs -n4|awk ' {i++;system("mkdir dir"i);system("mv "$0" -t dir"i)}'
kent$ tree
.
|-- dir1
| |-- 01.txt
| |-- 02.txt
| |-- 03.txt
| `-- 04.txt
|-- dir2
| |-- 05.txt
| |-- 06.txt
| |-- 07.txt
| `-- 08.txt
`-- dir3
|-- 09.txt
`-- 10.txt
#!/usr/bin/env bash
dir="${1-.}"
x="${2-4}"
let n=0
let sub=0
while IFS= read -r file ; do
if [ $(bc <<< "$n % $x") -eq 0 ] ; then
let sub+=1
mkdir -p "subdir$sub"
n=0
fi
mv "$file" "subdir$sub"
let n+=1
done < <(find "$dir" -maxdepth 1 -type f)
Works even when files have spaces and other special characters in their names.
精彩评论