简体   繁体   English

Shell,复制具有相似名称的文件

[英]Shell, copy files with similar names

I would like to copy a series of similar files from the current directory to the target directory, the files under the current directory are: 我想将一系列类似的文件从当前目录复制到目标目录,当前目录下的文件是:

prod07_sim0500-W31-0.2_velocity-models-2D_t80_f0001_ux.hst
prod07_sim0500-W31-0.2_velocity-models-2D_t80_f0001_uz.hst
prod07_sim0500-W31-0.2_velocity-models-2D_t80_f0002_ux.hst
prod07_sim0500-W31-0.2_velocity-models-2D_t80_f0002_uz.hst
prod07_sim0500-W31-0.2_velocity-models-2D_t80_f0003_ux.hst
prod07_sim0500-W31-0.2_velocity-models-2D_t80_f0003_uz.hst

Where sim is from sim0001 to sim0500 and f is from f0001 to f0009 . simsim0001sim0500ff0001f0009 I only need f0002 , f0005 and f0008 . 我只需要f0002f0005f0008 I write the following code: 我写下面的代码:

target_dir="projects/data"

for i in {0001..0500}; do
    for s in f000{2,5,8}; do
        files="[*]$i[*]$s[*]"
        cp $files target_dir
    done
done

I am very new to Shell, and wondering how to write the $files="[*]$i[*]$s[*]"$ , so that it could match only the f0002 , f0005 and f0008 . 我是Shell的新手,想知道如何编写$files="[*]$i[*]$s[*]"$ ,这样它只能匹配f0002f0005f0008 The reason why I also use for i in {0001..0500}; do 我之所以for i in {0001..0500}; do使用for i in {0001..0500}; do的原因也是for i in {0001..0500}; do for i in {0001..0500}; do is that the files are too large and I would like to make sure I could access some completed ones (for example, including all sim0001) in the beginning. for i in {0001..0500}; do是文件太大了,我想确保我可以在开始时访问一些已完成的文件(例如,包括所有的sim0001)。

Edit: changed for s in f0002 f0005 f0008; do 编辑: for s in f0002 f0005 f0008; do更改for s in f0002 f0005 f0008; do for s in f0002 f0005 f0008; do to f000{2,5,8} . for s in f0002 f0005 f0008; do f000{2,5,8}

What you need is globbing and a bit different quoting : 你需要的是通配 ,有点不同的引用

cp *"$i"*"$s"* "$target_dir"

Not storing this in a variable is intentional - it's faster and it's safe. 不将它存储在变量中是有意的 - 它更快,更安全。 If you end up with such a large list of files that you start running into system limits you'll have to look into xargs . 如果你最终得到如此大的文件列表,你开始遇到系统限制,你将不得不调查xargs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM