Saturday, April 10, 2010

looping through files with spaces in the filenames in bash

I sometimes have to transfer files with spaces in the names, I like using a for loop, but the usual way doesn’t work. Usual way:

for file in `find . -type f|grep .ext$`
/do/something/to $file
To get around this I use a while loop with a read instead. Using the read will read to the end of the line, enclosing within quotes escapes the spaces. Unusual way:
find . -type f|grep .ext$ |while read file
/do/something/to "$file"


1 comment:

Dani said...

If we want to find for example the ocupation of all pdf files, we can adapt it like this:

let sum=0;find . -type f -name *.pdf | while read file; do echo $file; let temp=$(du "$file" | awk '{print $1}'); let sum=$sum+$temp; echo "sum is "$sum" bytes";done


Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.