简体   繁体   中英

Bash Script to replicate files

I have 25 files in a directory. I need to amass 25000 files for testing purposes. I thought I could just replicate these files over and over until I get 25000 files. I could manually copy paste 1000 times but that seemed tedious. 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?

If you want to keep the extension of the files, you can use this. Assuming, you want to copy all txt -files:

#!/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.

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. This way, you can also do ${filename}_${i}${extension} to get files like a_23.txt , etc.

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).

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 )
  • in a cycle 1000 times copyes the original file to file-number.extension
  • it is for DRY-RUN, remove the echo if satisfied

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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