2012-06-27 338 views
0

假设一个特定的命令生成几个文件(我不知道这些文件的名称)。我想将这些文件移动到一个新文件夹中。如何在shell脚本中做到这一点?Shell脚本 - 将文件移动到文件夹中

我不能使用:

#!/bin/bash 
mkdir newfolder 
command 
mv * newfolder 

为CWD包含很多其他的文件。

+0

一个优雅的解决方案是将输出文件夹传递到命令,就像这样:'命令newfolder' ...如果你不能改变的命令,CD新的文件夹,把它的依赖关系进入新的文件夹;用正确的输入运行命令。 –

回答

2

第一个问题是,你可以运行commandnewfolder作为当前目录下生成在正确的地方它开头的文件:

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 
+0

谢谢戴夫韦伯,你写的答案的方式肯定会帮助我。我在提出这个问题时学到了新东西。非常感谢你。 – bioinformatician

1

如果您想将它们移动到一个子文件夹:

mv `find . -type f -maxdepth 1` newfolder 

设置一个-maxdepth 1只会查找当前目录中的文件并不会递归。传递-type f表示“查找所有文件”(“d”分别表示“查找所有目录”)。

+0

嗨carlspring,感谢您的反馈。你能解释我上面的脚本吗?其实我不明白'maxdepth' – bioinformatician

+0

我刚刚编辑了我的答案。 – carlspring

+1

如果文件夹中的文件太多,可能会发生错误,那么您可以尝试此版本的“find”: 'find。 -type f -maxdepth 1 -exec“mv {} newfolder \;”' – ipip

1

使用模式匹配:

$ 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 

来自实例here无耻地采取了在那里你可以找到一些关于它的更多有用的信息。

+0

嗨,matcheek,我对输出文件一无所知。所以模式匹配是不可能的。 – bioinformatician

1

假设您的命令每行打印一个名称,此脚本将工作。

my_command | xargs -I {} mv -t "$dest_dir" {} 
相关问题