How to Looping through the content of a file in Bash?

Looping through the content of a file in Bash?

In Bash, you can loop through the content of a file using a while loop and the read command.

Example

while IFS= read -r line; do
    echo "$line"
done < file.txt

Let's break down the syntax:

  • The while loop is used to iterate through the file file.txt.
  • The -r option to read disables interpreting backslashes. Without this option, backslashes will be treated as escape characters.
  • The IFS= option to read prevents leading/trailing whitespace from being trimmed.
  • $line is the variable that holds the current line being read.
  • The echo command outputs the current line.

You can replace echo "$line" with whatever command you want to run on each line of the file. For example, if you want to count the number of lines in the file, you can use this:

count=0
while IFS= read -r line; do
    ((count++))
done < file.txt
echo "Number of lines: $count"

This will output the number of lines in the file.

  1. Dynamic variable names in Bash
  2. How to parse command line arguments in Bash?
  3. Bash and shell script variable capitalization?
  4. How to get the directory where a Bash script is located from within the script itself?
  5. Parsing JSON with Unix tools
  6. Command not found error in Bash variable assignment
  7. How to set a variable to the output of a command in Bash?
  8. How to run Bash commands in Python?
  9. Extract filename and extension in Bash?