我使用此命令查找 mp3 文件并将其名称写入 log.txt:
find -name *.mp3 >> log.txt
我想使用 mv 命令移动文件,并且我想将其附加到日志文件中,以便它可以显示文件被移动的路径。
例如,如果 mp3 文件是 1.mp3 和 2.mp3,那么 log.txt 应该看起来像
1.mp3 >>>> /newfolder/1.mp3
2.mp3 >>>> /newfolder/2.mp3
如何使用 unix 命令来做到这一点?谢谢!
仅使用移动:
mv -v *.mp3 tmp/ > log.txt
或使用查找:
find -name '*.mp3' -exec mv -v {} test/ >> log.txt \;
您可能应该使用一些脚本语言,例如 Perl 或 Python;文本处理在 shell 中相当笨拙。
例如,在 Perl 中,您可以对 find 的输出进行后处理,然后打印出您所做的。
#!/usr/bin/perl -w
use strict;
use File::Find;
my @directories_to_search=("/tmp/");
sub wanted {
print "$File::Find::name >>> newdir/$_\n";
# do what you want with the file, e.g. invoke commands on it using system()
}
find(\&wanted, @directories_to_search);
用 Perl 或类似的方法做一些事情比在 shell 中更容易;特别是处理有趣的文件名(嵌入空格、特殊字符)更容易。不过,在调用 syste() 命令时要小心。
有关 File::Find 模块的文档,请参见http://perldoc.perl.org/File/Find.html。
GNU 查找
find /path -type f -iname "*.mp3" -printf "%f/%p\n" | while IFS="/" -r read filename path
do
mv "$path" "$destination"
echo "$filename >>> $destination/$filename " > newfile.txt
done
输出
$ touch 'test"quotes.txt'
$ ls -ltr
total 0
-rw-r--r-- 1 root root 0 2009-11-20 10:30 test"quotes.txt
$ mkdir temp
$ ls -l temp
total 0
$ find . -type f -iname "*\"*" -printf "%f:%p\n" | while IFS=":" read filename path; do mv "$filename" temp ; done
$ ls -l temp
total 0
-rw-r--r-- 1 root root 0 2009-11-20 11:53 test"quotes.txt