Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming files from CSV mapping using bash mangles files

Tags:

bash

scripting

I'm trying to rename auto-generated PDF files so that each one contains the name of the user it will go to, using a CSV map of the current name to it's new name, using what I thought was a straight forward and simple script in a bash shell.

The original files in the directory are named in the format Cover_Letter_1.pdf, Cover_Letter_2.pdf, etc. and in the CSV, they are mapped in the format:

Cover_Letter_1.pdf,Cover_Letter_User1.pdf
Cover_Letter_2.pdf,Cover_Letter_User2.pdf

I CD into the directory (where both the files and the CSV are), and tried this script:

sed 's/"//g' rename_list.csv | while IFS=, read orig new; do echo mv "$orig" "$new"; done

which returns a preview, showing exactly what I'd expected:

mv Cover_Letter_1.pdf Cover_Letter_User1.pdf
mv Cover_Letter_2.pdf Cover_Letter_User2.pdf

(sed 's/"//g' files.csv was for if there are quotes in the file names in the CSV file, there just happen to not be for this first group of files)

So, I would remove echo to run it for real, but the result is that it mangles the files, transforming them into generic .file format, with gibberish names like P4L8I7~B.file

I ran a "previewed" command (e.g. mv Cover_Letter_2.pdf Cover_Letter_User2.pdf) just to make sure that part of the script was correct (it was).

EDIT: I just thought to try running sed 's/"//g' rename_list.csv | while echo IFS=, read orig new; do echo mv "$orig" "$new"; done which results in it running indefinitely in a while loop with no apparent end. I thought that it would terminate when there were no more commas in the file, but, if I'm understanding correctly, it's just trying to continue reading lines forever.

like image 547
EtherealBug Avatar asked Aug 02 '26 02:08

EtherealBug


1 Answers

The problem was in the CSV file itself. The CSV was created in Windows and had CR LF EOL markers. Once I converted it to LF, it worked properly.

like image 149
EtherealBug Avatar answered Aug 04 '26 17:08

EtherealBug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!