Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

scripting

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?

like image 425
agnul Avatar asked Nov 06 '09 17:11

agnul


People also ask

How do I read a file in bash?

Syntax: Read file line by line on a Bash Unix & Linux shell The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line: while read -r line; do COMMAND; done < input. file. The -r option passed to read command prevents backslash escapes from being interpreted.

How do I list files in a directory in bash?

To see a list of all subdirectories and files within your current working directory, use the command ls .


1 Answers

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.

like image 59
Douglas Leeder Avatar answered Nov 03 '22 15:11

Douglas Leeder