Duplicating and renaming images using script
I need to duplicate and rename an image using a list of SKU codes from a spreadsheet as the unique name for each image. I have used the script from this answer Automate Duplicating and Renaming Images. I removed the filename line and changed "$line-$filename" to "$line". It works almost as expected but adds a ? to the end of every file, so it isn't saving as a .png, rather it saves as a .png?.
How do I get rid of the question mark...is there a simple fix to the script below or is it an issue with the txt file of SKU codes? Is it an encoding issue? Thank you so much.
#!/bin/bash
file=$1
prefixes=$2
while read line
do
cp $file "$line"
done < $prefixes
Your txt file probably has DOS/Windows-style line endings, which have a carriage return character at the end of each line (in addition to the linefeed that unix-style text files have). Unix tools generally mistake the carriage return for part of the line's content, and I suspect that's the extra character getting added to the filenames. You can check with file prefixfile.txt
(or whatever the filename is); if it says something about "CRLF line terminators", this is the problem.
If that is the problem, you can have the read
command strip the extra character with:
...
while IFS=$IFS$'\r' read -r line
do
...
Explanation: The read
command will trim whitespace at the beginning and end of lines. Whitespace is defined by the contents of the IFS
variable. Using IFS=$IFS$'\r'
adds carriage return to the list of whitespace characters, so read
will trim it.
Messing with IFS
is generally a bad idea, since it can have weird effects, but in this case the assignment is a prefix to the read
command, so it only affects that one command. This makes it much safer.