linux - 移动文件到不同的目录

标签 linux bash unix ubuntu

我正在尝试将指定目录中的媒体和其他文件移动到另一个目录,如果它不存在(文件将去的地方),则创建另一个目录,并创建一个目录,其余文件将具有不同的扩展名去。我的第一个问题是我的脚本没有创建新目录,也没有将文件移动到其他目录,我可以使用什么代码将具有不同扩展名的文件移动到一个目录?

这是我到目前为止所拥有的,纠正我错误的地方并帮助修改我的脚本:

#!/bin/bash
From=/home/katy/doc
To=/home/katy/mo #directory where the media files will go
WA=/home/katy/do # directory where the other files will go
 if [ ! -d "$To" ]; then
   mkdir -p "$To"
 fi
cd $From
find path -type f -name"*.mp4" -exec mv {} $To \;

最佳答案

我会像这样解决它:

#!/bin/bash
From=/home/katy/doc
To=/home/katy/mo # directory where the media files will go
WA=/home/katy/do # directory where the other files will go

cd "$From"
find . -type f \
| while read file; do
    dir="$(dirname "$file")"
    base="$(basename "$file")"
    if [[ "$file" =~ \.mp4$ ]]; then
      target="$To"
    else
      target="$WA"
    fi
    mkdir -p "$target/$dir"
    mv -i "$file" "$target/$dir/$base"
  done

注意事项:

  • mkdir -p如果目录已经存在,则不会提示,因此无需检查。
  • 在所有文件名两边加上双引号以防它们包含空格。
  • 通过管道输出 find进入while循环,你也避免被空格咬住,因为read会一直读到换行。
  • 您可以根据喜好修改正则表达式,例如\.(mp3|mp4|wma|ogg)$ .
  • 如果您不知道,$(...)将运行给定的命令并将其输出粘贴回 $(...) 的位置(称为命令替换)。几乎与`...`相同但稍微好一点(details)。
  • 为了测试它,输入echomv 前. (请注意,引号将在输出中消失。)

关于linux - 移动文件到不同的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8462443/

相关文章:

c - 在不忙等待的情况下实现互斥锁

linux - 如何显示用户输入的最长行

linux - 回显到文件时错误重定向到输出流失败。为什么?

bash - RPM %post 作为不同的用户

linux - 无法让 cron 脚本工作

Java:在 Linux 中使用包管理器中的 jar 库

python - 从嵌入式 python 代码获取输入时出错

bash `if $variable; then` 返回 `0: command not found`

python - 无需Windows专用工具即可向现有xlsx添加密码(无人值守)

linux - 如何按第三列中的数字对数据进行排序?