Run a command on each line in a file

You can cat a file and pipe it to a while loop in order to perform a command in each line in the file.

cat [filename] | while read line; do [command] "$line"; done

For example, if you have a text file, called filenames.txt, that contains line-separated filenames...

file1.txt
testdir/file2.txt
file3.txt

...you can do the following to run 'ls -l' on each filename in filenames.txt:

steph@slap ~/tmp/test $ cat filenames.txt | while read line; do ls -l "$line"; done
-rw-r--r-- 1 steph users 22 Sep 19 12:55 file1.txt
-rw-r--r-- 1 steph users 22 Sep 19 12:55 testdir/file2.txt
-rw-r--r-- 1 steph users 22 Sep 19 12:55 file3.txt

Or output their contents:

steph@slap ~/tmp/test1 $ cat filenames.txt | while read line; do cat "$line"; done
Contents of file1.txt
Contents of file2.txt
Contents of file3.txt

Last modified: 19/09/2008 Tags: (none)

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top