How can I read a list of filenames from a file in bash?


Question

I'm trying to write a bash script that will process a list of files whose names are stored one per line in an input file, something the likes of

find . -type f -mtime +15 > /tmp/filelist.txt
for F in $(cat /tmp/filelist.txt) ; do
  ...
done;

My problem is that filenames in filelist.txt may contain spaces, so the snipped above will expand the line

my text file.txt

to three different filenames, my, text and file.txt. How can I fix that?

1
31
11/6/2009 5:14:06 PM

Accepted Answer

Use read:

while read F  ; do
        echo $F
done </tmp/filelist.txt

Alternatively use IFS to change how the shell separates your list:

OLDIFS=$IFS
IFS="
"
for F in $(cat /tmp/filelist.txt) ; do
  echo $F
done
IFS=$OLDIFS

Alternatively (as suggested by @tangens), convert the body of your loop into a separate script, then use find's -exec option to run if for each file found directly.

41
11/6/2009 5:33:40 PM

You can do this without a temporary file using process substitution:

while read F
do
  ...
done < <(find . -type f -mtime +15)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon