我正在尝试将指定目录中的媒体和其他文件移动到另一个目录,如果它不存在(文件将去的地方),则创建另一个目录,并创建一个目录,其余文件将具有不同的扩展名去。我的第一个问题是我的脚本没有创建新目录,也没有将文件移动到其他目录,我可以使用什么代码将具有不同扩展名的文件移动到一个目录?
这是我到目前为止所拥有的,纠正我错误的地方并帮助修改我的脚本:
#!/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)。 - 为了测试它,输入
echo
在mv
前. (请注意,引号将在输出中消失。)
关于linux - 移动文件到不同的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8462443/