简体   繁体   中英

Shell Script, move each 2 files to each directory

I have 10 files from 1.txt to 10.txt and 5 folders abcde

I want to move my files in this way :

1.txt 2.txt to a
3.txt 4.txt to b
..
..
9.txt 10.txt to e

How Can I achieve this?

Here is the commands to do it.

count=0    # initialize the counter
declare -a files=(*.txt)     # put all the txt files in an array
# just print directories, and strip the unneeded /. in the returned string
declare -a dirs=($(ls -d */.|sed 's;/.;;')

# run through the array, moving each file
while [[ $count -le ${#files[@]} ]]; do
    mv ${files[$count]} ${dirs[$(($count/2))]}  
    ((++count))    # very important to increment the counters
done

The hard to read part is taking each file, and then moving it to the directory with the half that index. Since bash math rounds down and ignores remainders, this will give us index 0, 0, 1, 1, and so forth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM