Skip to content

Instantly share code, notes, and snippets.

@isurfer21
Last active July 3, 2024 06:17
Show Gist options
  • Save isurfer21/ba2b81c8720ef3e7a82f4a105539dc8e to your computer and use it in GitHub Desktop.
Save isurfer21/ba2b81c8720ef3e7a82f4a105539dc8e to your computer and use it in GitHub Desktop.
A CLI tool is a bash script that creates multiple copies of a specified file, renaming each copy with an incrementing number.
#!/bin/bash
# Check if the required arguments are provided
if [ $# -ne 2 ]; then
echo "Usage: ${0##*/} <file-path> <copy-count>"
exit 1
fi
# Assign the arguments to variables
file_path=$1
copy_count=$2
# Check if the file exists
if [ ! -f "$file_path" ]; then
echo "Error: File not found: $file_path"
exit 1
fi
# Get the file name and directory
file_name=$(basename "$file_path")
file_dir=$(dirname "$file_path")
# Generate the copies
for ((i=1; i<=$copy_count; i++)); do
new_file_name="${file_name%.${file_name##*.}}_${i}.${file_name##*.}"
cp "$file_path" "$file_dir/$new_file_name"
done
@isurfer21
Copy link
Author

copy-file.sh

A bash script that creates multiple copies of a specified file, renaming each copy with an incrementing number. This command is useful for quickly duplicating files while maintaining a consistent naming convention. Simply provide the file path and desired number of copies as arguments, and copy-file will generate the duplicates in the same directory.

Let me explain how the script works:

  1. The script checks if the required arguments (file-path and copy-count) are provided. If not, it displays the usage message and exits.
  2. It assigns the arguments to variables file_path and copy_count.
  3. It checks if the file exists. If not, it displays an error message and exits.
  4. It extracts the file name and directory from the file path using basename and dirname commands.
  5. It generates the copies using a for loop. For each iteration, it creates a new file name by appending an incrementing number to the original file name (e.g., file.txt becomes file_1.txt, file_2.txt, etc.). It then copies the original file to the new file using cp command.

To use the script, save it to a file (e.g., copy_file.sh), make it executable with chmod +x copy_file.sh, and then run it with the file path and copy count as arguments, like this:

copy_file.sh /path/to/file.txt 5

This will generate 5 copies of the file file.txt with names file_1.txt, file_2.txt,..., file_5.txt in the same directory.

@isurfer21
Copy link
Author

Tip

To rename the original file by appending it with _0 to make it on top of the sequence, you can add below code at the end of the copy-file.sh script

new_file_name="${file_name%.${file_name##*.}}_0.${file_name##*.}"
mv "$file_path" "$file_dir/$new_file_name"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment