Bash – While Loop: Done < Command Instead of Done < File

bash

For moving all files in sub folders into the current folder I use this script

while read f
do
    mv "$f" .
done < file_list

this works great but i have to generate the file_list with

find . -name *.avi > file_list

what i want is to add the command directly to my while loop

while read f
do
    mv "$f" .
done < find . -name *.avi

but bash tells me -bash: syntax error near unexpected token `.'

What is an easy solution to pipe the find command into my while loop?

Best Answer

proper way to do this is pipe

find . -name '*.avi' |
while read f
do
    mv "$f" .
done 

the result from first command "find . -name *.avi" will feed the second.

This is call a pipe (from the symbol | ). You can think of pipe as a temporary file like

find . -name '*.avi' > file1.tmp
while read f
do
    mv "$f" .
done < file1.tmp
rm file1.tmp

As pointed out filename with space or newline are likely to cause error.

If the only purpose is to move file, use @Terdon's commands.

Also you must quote *.avi or it will break on second run.

find: paths must precede expression: `foo.avi' 
find: possible unquoted pattern after predicate `-name'?
Related Question