Friday, May 3, 2024
5
rated 0 times [  5] [ 0]  / answers: 1 / hits: 958  / 2 Years ago, sat, march 5, 2022, 5:04:24

I want to learn more so I have tried to script more than just using the terminal. I know rename and I can rename image files with rename 's/ /_/g' *.jpg but when I write it in a shell script to point at a directory:



DIRECTORY="/foo/bar"

for imgfile in $(find $DIRECTORY -type f -name *.jpg); do
echo 'replacing whitespace in' $(basename $imgfile)
rename -f 's/ /_/g' *.jpg
done


it doesn't work and the terminal will take a file (example: 1234 abcd.jpg) and echo abcd.jpg. So where am I going wrong?


More From » command-line

 Answers
4

Spaces in filenames are evil.



I see three problems with the script:




  1. when doing the for... loop, you will have two different values when you find a file with space. i.e., if you have the files "file1 1.jpg" and "file2 2.jpg" and you do:



    for i in $(find . -type f -name *.jpg); do 
    echo $i
    done


    You'll have



    ./file1 
    1.jpg
    ./file2
    2.jpg


    because the shell breaks the argument at spaces. The output of the $(find ...) command will be



    ./file1 1.jpg 
    ./file2 2.jpg


    Which are four words for the command for to be assigned at $i --- by default the shell treats spaces and newlines in the same way when expanding.



    You can circumvent this changing the IFS char.



    Your first line could look like:



    IFS=$'
    ' find $DIRECTORY -type f -name *.jpg | while read -r imgfile; do

  2. you are feeding the for loop with a single file name, so you should say:



    rename -f 's/ /_/g' "$imgfile"


    otherwise *.jpg is expanded in the current directory, and not in $DIRECTORY (and note the quotes --- given that $imgfile is going to have spaces in it).


  3. even then, if $DIRECTORY has some path component with spaces in it, the rename will fail (there will be intermediate directories that do not exist).


  4. suggestion (keeping it simple):



    DIRECTORY="/foo/bar"
    cd $DIRECTORY
    rename -f 's/ /_/g' *.jpg


    doesn't do what you want?




Added: my script (created ages ago, when there was no rename in Unix), is this --- it will remove spaces and tab in all files in current dir that have them in the name:



# 
ls -1 | grep -E " | " | while read i; do
a=`echo $i | tr " " "__"`
mv -v "$i" $a
done


Added++: this link I found researching this answer is excellent.


[#28329] Sunday, March 6, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
poefor

Total Points: 379
Total Questions: 95
Total Answers: 115

Location: Serbia
Member since Tue, Jul 26, 2022
2 Years ago
;