gpt-4.1-mini-2025-04-14· openai
from WildChat-4.8M
File list.txt contains list of files separated by newline. How to run command for each…
- User
File list.txt contains list of files separated by newline. How to run command for each file in list in linux?
- Assistant
If you have a file
list.txtthat contains filenames separated by newlines, and you want to run a command for each file listed, there are several ways to do this in Linux. Here are some common methods:
Using a
whileloopbashwhile IFS= read -r file; do command "$file" done < list.txt- This reads each line from
list.txt. IFS=and-rhandle filenames with spaces or special characters correctly.- Replace
commandwith the actual command you want to run on each file.
Using
xargsbashxargs -a list.txt -n 1 command-a list.txt: read input fromlist.txt.-n 1: runcommandonce per argument.- Note: This may break if filenames contain spaces or special characters.
For safer handling of spaces, you can use:
bashcat list.txt | while IFS= read -r file; do command "$file" done
Using
forloop with command substitution (not recommended for filenames with spaces)bashfor file in $(cat list.txt); do command "$file" done
Example: print each filename
bashwhile IFS= read -r file; do echo "Processing: $file" done < list.txt
Summary
The best and safest way to run a command for each file listed in
list.txtis thewhileloop method:bashwhile IFS= read -r file; do command "$file" done < list.txtReplace
commandwith your desired command. - This reads each line from