Bash read file names from a text file and take action

‮www‬.lautturi.com
Bash read file names from a text file and take action

To read a list of file names from a text file and take action on them, you can use a combination of the cat command, xargs command, and bash loop.

First, you can use the cat command to read the contents of the text file and print them to the terminal. For example, if your text file is named filelist.txt, you can use the following command to print the file names in the text file to the terminal:

cat filelist.txt

Next, you can use the xargs command to take the output of the cat command and pass it as arguments to another command. For example, if you want to delete all of the files listed in the text file, you can use the following command:

cat filelist.txt | xargs rm -f

This will read the file names from the text file, and pass them as arguments to the rm command, which will delete each file.

Finally, you can use a bash loop to iterate over the file names in the text file and take some action on each file. For example, the following bash script will read the file names from the text file, and print the name of each file to the terminal:

#!/bin/bash

# Read the file names from the text file, one line at a time
while read filename; do
  # Print the name of each file to the terminal
  echo $filename
done <filelist.txt

This script uses a while loop to iterate over the file names in the text file, and the echo command to print each file name to the terminal.

Overall, you can use the cat command, xargs command, and bash loop to read a list of file names from a text file and take action on them. These commands and the bash loop can be combined in different ways to perform a variety of actions on the files listed in the text file.

Created Time:2017-10-16 14:38:39  Author:lautturi