Linux Tutorials

Bash learn file names from a textual content file and take motion

SEOClerks

I must learn a listing of file names from a textual content file named enter.txt and take motion every file title. How do I learn file names from a textual content file and say run /bin/foo command on every file? How do I learn filenames from a textual content file and take sure motion on these information?

Introduction – Typically it’s good to learn a file line-by-line and course of knowledge. It’s a fairly frequent process for Linux and Unix sysadmin shell scripts. You must use a bash whereas loop and the learn command.

Bash learn file names from a textual content file

The syntax is as follows to learn filenames from a textual content file:

whereas IFS= learn -r file; do
echo “Do one thing on $file …”
performed < “filenames.txt”

OR

enter=“knowledge.txt”
whereas IFS= learn -r file; do
printf ‘%sn’ $file
performed < $enter

Learn filenames from a textual content file utilizing bash whereas loop

Allow us to create a brand new file named enter.txt with the filename on every line utilizing the cat command or vim command:
cat > enter.txt
Append knowledge:

foo.txt
bar.txt
delta.jpg
nixcraft.brand.png
gross sales.pdf
/and so on/resolv.conf
/house/vivek/Paperwork/fy-19-2020.ods
#/house/vivek/Paperwork/yearly-sales-data.ods

Associated: How To Create Recordsdata in Linux From a Bash Shell Immediate

Here’s a pattern bash shell script to learn a file line-by-line:

#!/bin/bash
# Identify – script.sh
# Writer – Vivek Gite beneath GPL v2.x+
# Utilization – Learn filenames from a textual content file and take motion on $file
# —————————————————————-
set -e
in=$
 
[ ! -f $in ] &&
 
whereas IFS= learn -r file
do
echo “Engaged on $file …”
performed < $

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

Additionally it is potential to disregard filenames beginning with #

Right here is an up to date model of the script:

#!/bin/bash
# Identify – script.sh (bash learn file names checklist from file)
# Writer – Vivek Gite beneath GPL v2.x+
# Utilization – Learn filenames from a textual content file and take motion on $file
# —————————————————————-
set -e
in=$
 
[ ! -f $in ] &&
 
whereas IFS= learn -r file
do
## keep away from commented filename ##
[[ $file = #* ]] && proceed
echo “Working rm $file …”
performed < $

Conclusion

You realized the right way to learn a listing of filenames from a file in bash and take motion on them.

Posted by: Vivek Gite

The creator is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a coach for the Linux working system/Unix shell scripting. Get the newest tutorials on SysAdmin, Linux/Unix and open supply matters through RSS/XML feed or weekly electronic mail e-newsletter.

Source link

Related Articles

Back to top button