Space for

So your friend sent you a batch of tiffs to be converted into jpg’s (using ImageMagick‘s convert command). However your friend (who is not so geeky as you) uses spaces in filenames (which is a deadly sin), like in

  • First photo of birthday.tiff
  • Second photo.tiff

You wanted to use a shell for loop, but the obvious

$ for i in `find . -name *tiff` ; do convert "$i" "${i%tiff}jpg" ; done

produces garbage (try it). This is just one of the consequences of your friend’s carelessness.

But there is a solution. IFS (Internal Field Separator) is a shell variable controlling what character(s) delimit a ‘field’ in a line (usually a space, or a tab, but may be any string: each character in it will be considered a ‘separator’).

In our case, we need to tell the shell to use just newlines. However, the obvious IFS="\n" does not work (it is seen as an ‘n’ by the shell). One needs to use a true newline:

$ IFS='
' ; for i in `find . -name *tiff` ; do convert "$i" "${i%tiff}jpg" ; done

does the job. Notice that you really need to type the newline between the two quotation marks.

Hope this helps.


  • On 01.29.09 pgas said:

    On some shells (bash, ksh93) you can use IFS=$’\n’.

    A while read loop might be a bit better, since you don’t need to load all the filenames in memory:

    find -name ‘*.tiff’ | IFS= while read -r file;do echo “$file”;done

    It still fails for the filenames with newlines, there are a numbers of workarounds for instance:

    find . -name ‘*.tiff’ -exec sh -c ‘convert “$1” “${1%tiff}jpg”‘ – {} \;

  • On 01.29.09 pgas said:

    err the while loop should have been:
    find -name ‘*.tiff’ | while IFS= read -r file;do echo “$file”;done

  • On 01.29.09 Pedro Fortuny said:

    Hi, pgas, thanks. I like the while pipe. And the comment about newlines in filenames! One can’t assume ANYthing…


  • On 02.04.09 commandliners » Batch convert RTF to PDF said:

    […] to me. Read the details if you need to do something similar. [NB: This has been edited following pgas’ piped-while suggestion. There was a for loop with the find inside inverted […]

  • On 03.06.09 commandliners » Accents everywhere (to be removed, obviously) said:

    […] of the piped while you see above. Thanks to Pierre Gaston for his comment. Tagged: accent, find, IFS, maxdepth, mindepth, mv, regex, […]

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*Required Fields