Reputation: 3671
I'm brand new to Unix and I'm learning how powerful it can be to run scripts on automating file duplication, etc. I've had help creating the initial script (credit where credit's due: https://apple.stackexchange.com/questions/101436/automate-duplicating-and-renaming-images/101437) but now I'm wondering how to generate a specific directory name while duplicating the files. Here's the original script:
#!/bin/bash
file=$1
prefixes=$2
filename=`basename "$file"`
while read line
do
cp $file "$line-$filename"
done < $prefixes
I basically call the script and then have the prefixes from a text file that's in the same directory append a string to the beginning of the new file that's made. What I would like to do is also create a directory with the original file name so I can then have all the duplicate automatically placed in the new folder. I had tried something like this:
#!/bin/bash
file=$1
prefixes=$2
filename=`basename "$file"`
while read line
do
mkdir $filename
cp $file "$filename/$line-$filename"
done < $prefixes
But that doesn't seem to work. You'll see my intentions though. I would like a directory with the same name as the original file and then have all new images copied into that directory. The command I use in Terminal on Mac OSX is ./copier.sh myimage.jpeg prefixes.txt
.
I've gotten the script to create a directory if I just use something like mkdir test
but that won't do any good since I'll have to go in and change the directory name every time I run the script.
Let me know if you have any questions. I'm sorry if I'm making some major errors, I'm just having trouble finding the solution to this. Thanks for your help!
Upvotes: 0
Views: 381
Reputation: 75608
If $filename
is in the same directory you won't be able to create the directory since a file already exists. You could consider using a different name like the filename without an extension.
#!/bin/bash
file=$1
prefixes=$2
filename=${file##*/} ## Better than using an external binary like basename.
dir=${filename%%.*} ## Remove extension.
mkdir -p "$dir" || exit 1 ## Only need to create it once so place it outside the loop. And `$dir` might already have been made so use `-p`. This would also make the code exit if `mkdir` fails.
while read -r line ## Use -r to read lines in raw form
do
cp "$file" "$dir/$line-$filename"
done < "$prefixes"
Consider quoting your variables properly around ""
as well .
Upvotes: 1