Last active
July 3, 2024 06:17
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
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
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:
To use the script, save it to a file (e.g.,
copy_file.sh
), make it executable withchmod +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.