Copying and renaming files from one destination to another is easily accomplished by the cp command in Linux. However, it becomes more complex when we want to copy and rename all files in the same directory while assigning a serial number to each copy. In this article, we provide a shell script to copy and rename files present in a directory, adding a unique serial number to each copy.
The provided shell script is designed to copy and rename .txt files in the current directory multiple times. You can copy and rename any file.
#!/bin/bash
# Define the number of copies to create
num_copies=50
# Loop through each pdbqt file in the current directory
for file in *.txt; do
# Get the base name of the file (without extension)
base_name="${file%.*}"
# Copy the file multiple times and rename them
for ((i = 1; i <= num_copies; i++)); do
cp "$file" "${base_name}_${i}.txt"
done
done
The script achieves this by performing the following steps:
- Defining the Number of Copies: The variable
num_copiesis set to50, indicating that each.txtfile will be copied 50 times. - Looping Through Each
.txtFile: The script uses aforloop to iterate over all files in the current directory with the.txtextension. - Extracting the Base Name: For each file, the script extracts the base name (i.e., the filename without the extension) using parameter expansion
${file%.*}. - Copying and Renaming Files: Another
forloop runs from 1 to 50 (num_copies), copying the original file and renaming each copy with an incremented suffix. Thecpcommand is used for copying, and the new filenames follow the patternbase_name_i.txt, whereiranges from 1 to 50.
Run the script
Ensure to replace the extension in the script according to your needs. Save the script with .sh extension and run it as follows:
$ chmod +x copy_rename.sh
$ ./copy_rename.sh
It will start copying and renaming files instantly.
