Search code examples
bashfilesystemsjpegwebp

How to execute command on files with spaces in them?


I am dealing with a legacy codebase where we're trying to convert all jpeg/png files to webp format using the cwebp command. Unfortunately, a lot of the image files were saved with spaces in the name. Example: i am poorly named.jpg

So when running the following bash script to find all jpegs in the directory and loop through and convert them the words separated by spaces are treated as another file so the image never gets converted. We don't want to remove the whitespaces, but just create a webp file with the exact same name.

files=$(find ./ -type f -name  "*.jpg")
for jpg in $files
do
  webp="${jpg/%jpg/webp}";
  if [ ! -f $webp ]; then
    echo "The webp version does not exist";
    cwebp -q 80 "$jpg" -o "$webp";
  fi
done

I've tried placing jpg=$(printf '%q' "$jpg") immediately after the do in the above code as well as other things.

I expect i am poorly named.webp to be created if file i am poorly named.jpg exists.


Solution

  • But there is no real reason to store all filenames. So an alternative is:

    find ./ -type f -name  "*.jpg" | while read jpg
    do 
    ....
    

    But this works only, if a filename contains no linefeed. For files with linesfeeds there are other solutions. Ask for it if needed.