How to copy and rename files simultaneously in same directory in Ubuntu (Linux)?

Dr. Muniba Faiza
2 Min Read

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:

  1. Defining the Number of Copies: The variable num_copies is set to 50, indicating that each .txt file will be copied 50 times.
  2. Looping Through Each .txt File: The script uses a for loop to iterate over all files in the current directory with the .txt extension.
  3. Extracting the Base Name: For each file, the script extracts the base name (i.e., the filename without the extension) using parameter expansion ${file%.*}.
  4. Copying and Renaming Files: Another for loop runs from 1 to 50 (num_copies), copying the original file and renaming each copy with an incremented suffix. The cp command is used for copying, and the new filenames follow the pattern base_name_i.txt, where i ranges 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.


 

Share This Article
Dr. Muniba is a Bioinformatician based in New Delhi, India. She has completed her PhD in Bioinformatics from South China University of Technology, Guangzhou, China. She has cutting edge knowledge of bioinformatics tools, algorithms, and drug designing. When she is not reading she is found enjoying with the family. Know more about Muniba
Leave a Comment

Leave a Reply