假设一个特定的命令生成了几个文件(我不知道这些文件的名称)。我想将这些文件移动到一个新文件夹中。如何在shell脚本中做到这一点?
我不能使用:
#!/bin/bash
mkdir newfolder
command
mv * newfolder
因为 cwd 还包含许多其他文件。
第一个问题是你能不能作为当前目录运行command
以newfolder
在它开始的正确位置生成文件:
mkdir newfolder
cd newfolder
command
或者如果command
不在路径中:
mkdir newfolder
cd newfolder
../command
如果您不能这样做,那么您需要捕获前后文件的列表并进行比较。这样做的一种不优雅的方法如下:
# Make sure before.txt is in the before list so it isn't in the list of new files
touch before.txt
# Capture the files before the command
ls -1 > before.txt
# Run the command
command
# Capture the list of files after
ls -1 > after.txt
# Use diff to compare the lists, only printing new entries
NEWFILES=`diff --old-line-format="" --unchanged-line-format="" --new-line-format="%l " before.txt after.txt`
# Remove our temporary files
rm before.txt after.txt
# Move the files to the new folder
mkdir newfolder
mv $NEWFILES newfolder
如果您想将它们移动到子文件夹中:
mv `find . -type f -maxdepth 1` newfolder
设置 a-maxdepth 1
只会查找当前目录中的文件,不会递归。传入-type f
意味着“查找所有文件”(“d”分别表示“查找所有目录”)。
使用模式匹配:
$ ls *.jpg # List all JPEG files
$ ls ?.jpg # List JPEG files with 1 char names (eg a.jpg, 1.jpg)
$ rm [A-Z]*.jpg # Remove JPEG files that start with a capital letter
示例无耻地取自此处,您可以在其中找到更多有用的信息。
假设您的命令打印出每行一个名称,则此脚本将起作用。
my_command | xargs -I {} mv -t "$dest_dir" {}