linux - Shell脚本,将每2个文件移动到每个目录

标签 linux bash shell unix

我有从 1.txt 到 10.txt 的 10 个文件和 5 个文件夹 a b c d e

我想以这种方式移动我的文件:

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

我怎样才能实现这个目标?

最佳答案

这是执行此操作的命令。

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

难以阅读的部分是获取每个文件,然后将其移动到具有该索引一半的目录。由于 bash 数学会向下舍入并忽略余数,因此这将为我们提供索引 0、0、1、1 等。

关于linux - Shell脚本,将每2个文件移动到每个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36699502/

相关文章:

c++ - 右侧的非法 token ::

linux - 连接丢失时自动关闭 PuTTY

bash - 仅使用 awk 在两个正则表达式之间打印

linux - 在分配变量后,稍后使用变量引用扩展字符串

linux - SED - 删除后跟换行 (\n) 的字符串

c - 批量消息传输 USB Linux

bash - 使用 Bash 在特定行之前插入多行文本

bash - 在 Bash 脚本中计算数学表达式

linux - 目录中的占位符 - awk 中的 printf

python - 在paramiko的shell中找不到Unifi的命令