This may be a duplicate of Duplicate file x times in command shell and is definitely a duplicate of How to duplicate a file a number of times while embedding an index in each file but the person who posted the answer was last seen in 2017 and I'd like to know how I can use this as a function in zsh so that I can call it on a file with any extension (not just txt files) like so: cpx file.ext n
where n
is the number of copies to make. Also, how I can separate the filename and file extension.
This was the answer for txt files only:
#!/bin/sh
orig=ascdrg3.txt # start with this file
in=$orig
count=1 #loop variable
max=5 #number of files to create
while test "$count" -le "$max" ; do
# Remove extension
base=$(basename "$in" .txt)
# get the prefix
prefix=$(expr substr "$base" 1 $((${#base}-1)))
# get last letter
last=$(expr substr "$base" ${#base} 1)
while true ;
do
# Advance letter, while the file doesn't exist
last=$(echo "$last" | tr A-Z B-ZA)
last=$(echo "$last" | tr a-z b-za)
last=$(echo "$last" | tr 0-9 1-90)
# construct new file name
new="$prefix$last.txt"
# continue if it doesn't exist
# (otherwise, advance the last letter and try again)
test -e "$new" || break
test "$new" = "$orig" \
&& { echo "error: looped back to original file" >&2 ; exit 1; }
done
# Create new file
cp "$orig" "$new"
# Modify first line of new file
sed -i "1s/\$/number($count,$max)/" "$new"
# Advance counter
count=$((count+1))
# loop again
in=$new
done
Is there a much smaller way to do this?
What I want is: cpx hello.py 3
should create hello1.py hello2.py hello3.py