Linux

Bash read file names from a text file and take action

I need to read a list of file names from a text file named input.txt and take action each file name. How do I read file names from a text file and say run /bin/foo command on each file? How do I read filenames from a text file and take certain action on those files?

Introduction – Often you need to read a file line-by-line and process data. It is a pretty common task for Linux and Unix sysadmin shell scripts. You need to use a bash while loop and the read command.

Bash read file names from a text file

The syntax is as follows to read filenames from a text file:

OR

Read filenames from a text file using bash while loop

Let us create a new file named input.txt with the filename on each line using the cat command or vim command:
cat > input.txt
Append data:

Related: How To Create Files in Linux From a Bash Shell Prompt

Here is a sample bash shell script to read a file line-by-line:

Simple run it as follows:
./script.sh
Bash read file names from a text file and take action

It is also possible to ignore filenames starting with #

Here is an updated version of the script:

Conclusion

You learned how to read a list of filenames from a file in bash and take action on them.

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close