loop through lines of file bash

Bash Loop Through Content of File

Shell scripts allow you to automate many tasks including reading of file contents. Generally, most developers read files at one go, using shell scripts but sometimes you may need to loop through the content of file, line by line. In this article, we will learn how to iterate through file contents line by line.


Bash Loop Through Content of File

There are a couple of simple ways to loop through file contents in shell script. Let us say you have a file data.txt. Then here is a simple way to read and echo the file contents line by line.

while read p; do
  echo "$p"
done <data.txt

The while loop goes through the file data.txt line by line. Variable $p stores the present line of file in each iteration.

The above approach works in most cases, but it can lead to trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it’s missing a terminating linefeed. If these are concerns for you, then you can use the following code instead.

while IFS="" read -r p || [ -n "$p" ]
do
  printf '%s\n' "$p"
done < data.txt

In the above code, the while loop goes through each line of code, one by one. We set IFS (input field separator) to empty string to preserve white spaces, and prevent them from being trimmed.

In this article, we have learnt how to loop through content of file, line by line, and display their content. You can run these commands on terminal or within a shell script, as per your requirement.

Also read:

How to Update Row Based on Previous Row in MySQL
How to Disable Commands in Linux
How to Install Printer in Ubuntu Via GUI
How to Increase SSH Connections in Linux
How to Disable Root Login in Linux

Leave a Reply

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