简体   繁体   English

用于复制文件的 Bash 脚本

[英]Bash Script to replicate files

I have 25 files in a directory.我在一个目录中有 25 个文件。 I need to amass 25000 files for testing purposes.我需要收集 25000 个文件用于测试目的。 I thought I could just replicate these files over and over until I get 25000 files.我以为我可以一遍又一遍地复制这些文件,直到得到 25000 个文件。 I could manually copy paste 1000 times but that seemed tedious.我可以手动复制粘贴 1000 次,但这似乎很乏味。 So I thought I could write a script to do it for me.所以我想我可以写一个脚本来为我做这件事。 I tried我试过

cp * .

As a trial but I got an error that said the source and destination file are the same.作为试验,但我收到一个错误,说源文件和目标文件相同。 If I were to automate it how would i do it so that each of the 1000 times the new files are made with unique names?如果我要自动化它,我将如何做到这一点,以便新文件的 1000 次中的每一个都具有唯一的名称?

If you want to keep the extension of the files, you can use this.如果要保留文件的扩展名,可以使用它。 Assuming, you want to copy all txt -files:假设您要复制所有txt文件:

#!/bin/bash

for f in *.txt
do
  for i in {1..10000}
  do
    cp "$f" "${f%.*}_${i}.${f##*.}"
  done
done

As discussed in the comments, you can do something like this:正如评论中所讨论的,您可以执行以下操作:

for file in *
do
   filename="${file%.*}"    # get everything up to last dot
   extension="${file##*.}"  # get extension (text after last dot)
   for i in {00001..10000}
   do
       cp $file ${filename}${i}${extension}
   done
done

The trick for i in {00001..10000} is used to loop from 1 to 10000 having the number with leading zeros. for i in {00001..10000}技巧for i in {00001..10000}从 1 到 10000 循环,其中数字带有前导零。

The ${filename}${i}${extension} is the same as $filename$i$extension but makes more clarity over what is a variable name and what is text. ${filename}${i}${extension}$filename$i$extension相同,但更清楚什么是变量名和什么是文本。 This way, you can also do ${filename}_${i}${extension} to get files like a_23.txt , etc.这样,您还可以执行${filename}_${i}${extension}来获取a_23.txt等文件。

In case your current files match a specific pattern, you can always do for file in a* (if they all are on the a + something format).如果您当前的文件与特定模式匹配,您始终可以for file in a*执行for file in a* (如果它们都采用a + something格式)。

You could try this:你可以试试这个:

for file in *; do for i in {1..1000}; do cp $file $file-$i; done; done;

It will append a number to any existing files.它将在任何现有文件中附加一个数字。

The next script下一个脚本

for file in *.*
do
    eval $(sed 's/\(.*\)\.\([^\.]*\)$/base="\1";ext="\2";/' <<< "$file")
    for n in {1..1000}
    do
        echo cp "$file" "$base-$n.$ext"
    done
done

will:将要:

  • take all files with extensions *.*获取所有扩展名为*.*文件
  • creates the basename and extension ( sed )创建基本名称和扩展名 ( sed )
  • in a cycle 1000 times copyes the original file to file-number.extension在一个循环中 1000 次将原始文件复制到 file-number.extension
  • it is for DRY-RUN, remove the echo if satisfied它是用于 DRY-RUN,如果满足则去除回声

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

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