Linux Shell 脚本 - 将文件移动到文件夹中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11223671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:05:02  来源:igfitidea点击:

Shell script - move files into folder

linuxshell

提问by bioinformatician

Suppose a particular command generates few files (I dont know the name of these files). I want to move those files into a new folder. How to do it in shell script?

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

i can't use :

我不能使用:

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

as the cwd contains lot of other files as well.

因为 cwd 还包含许多其他文件。

采纳答案by Dave Webb

The first question is can you just run commandwith newfolderas the current directory to generate the files in the right place it begin with:

第一个问题是,您是否可以将commandnewfolder作为当前目录运行以在其开头的正确位置生成文件:

mkdir newfolder
cd newfolder
command 

Or if commandis not in the path:

或者如果command不在路径中:

mkdir newfolder
cd newfolder
../command 

If you can't do this then you'll need to capture lists of before and after files and compare. An inelegant way of doing this would be as follows:

如果您不能这样做,那么您将需要捕获文件前后的列表并进行比较。这样做的一种不优雅的方式如下:

# 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

回答by carlspring

If you'd like to move them into a sub-folder:

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

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

Setting a -maxdepth 1will only find the files in the current directory and will not recurse. Passing in -type fmeans "find all files" ("d" would, respectively, mean "find all directories").

设置a-maxdepth 1只会查找当前目录下的文件,不会递归。传入-type f意味着“查找所有文件”(“d”分别表示“查找所有目录”)。

回答by matcheek

use pattern matching:

使用模式匹配:

  $ 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

Example shamelessly taken from herewhere you can find some more useful information about it.

无耻地从这里获取的示例,您可以其中找到有关它的更多有用信息。

回答by Peter.O

Assuming that your command prints out names with one per line, this script will work.

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

my_command | xargs -I {} mv -t "$dest_dir" {}