[英]Move files to directories based on extension
I am new to Linux.我是 Linux 新手。 I am trying to write a shell script which will move files to certain folders based on their extension , like for example in my downloads folder, I have all files of mixed file types.
我正在尝试编写一个 shell 脚本,它将根据文件的扩展名将文件移动到某些文件夹,例如在我的下载文件夹中,我拥有混合文件类型的所有文件。 I have written the following script
我写了以下脚本
mv *.mp3 ../Music
mv *.ogg ../Music
mv *.wav ../Music
mv *.mp4 ../Videos
mv *.flv ../Videos
How can I make it run automatically when a file is added to this folder?将文件添加到此文件夹时,如何使其自动运行? Now I have to manually run the script each time.
现在我每次都必须手动运行脚本。
One more question, is there any way of combining these 2 statements还有一个问题,有没有办法将这两个陈述结合起来
mv *.mp3 ../../Music
mv *.ogg ../../Music
into a single statement?成一个单一的声明? I tried using
||
我尝试使用
||
(C programming 'or' operator) and comma but they don't seem to work. (C 编程“或”运算符)和逗号,但它们似乎不起作用。
There is no trigger for when a file is added to a directory.将文件添加到目录时没有触发器。 If the file is uploaded via a webpage, you might be able to make the webpage do it.
如果文件是通过网页上传的,您或许可以让网页上传。
You can put a script in crontab to do this, on unix machines (or task schedular in windows).您可以在 unix 机器上(或 Windows 中的任务计划)在 crontab 中放置一个脚本来执行此操作。 Google crontab for a how-to.
谷歌 crontab 的操作方法。
As for combining your commands, use the following:至于组合您的命令,请使用以下命令:
mv *.mp3 *.ogg ../../Music
You can include as many different "globs" (filenames with wildcards) as you like.您可以根据需要包含任意多个不同的“globs”(带通配符的文件名)。 The last thing should be the target directory.
最后一件事应该是目标目录。
Two ways:两种方式:
find . -name '*mp3' -or -name '*ogg' -print | xargs -J% mv % ../../Music
find . -name '*mp3' -or -name '*ogg' -exec mv {} ../Music \\;
The first uses a pipe and may run out of argument space;第一个使用管道,可能会耗尽参数空间; while the second may use too many forks and be slower.
而第二个可能使用太多叉子并且速度较慢。 But, both will work.
但是,两者都会起作用。
I like this method:我喜欢这个方法:
#!/bin/bash
for filename in *; do
if [[ -f "$filename" ]]; then
base=${filename%.*}
ext=${filename#$base.}
mkdir -p "${ext}"
mv "$filename" "${ext}"
fi
done
Another way is:另一种方式是:
mv -v {*.mp3,*.ogg,*.wav} ../Music
mv -v {*.mp4,*.flv} ../Videos
PS: option -v shows what is going on (verbose). PS:选项 -v 显示正在发生的事情(详细)。
You can use for loop to traverse through folders and subfolders inside the source folder.您可以使用for 循环遍历源文件夹内的文件夹和子文件夹。 The following code will help you move files in pair from "/source/foler/path/" to "/destination/fodler/path/".
以下代码将帮助您将文件从“/source/foler/path/”成对移动到“/destination/fodler/path/”。 This code will move file matching their name and having different extensions.
此代码将移动与其名称匹配并具有不同扩展名的文件。
for d in /source/folder/path/*; do
ls -tr $d |grep txt | rev | cut -f 2 -d '.' | rev | uniq | head -n 4 | xargs -I % bash -c 'mv -v '$d'/%.{txt,csv} /destination/folder/path/'
sleep 30
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.