linux - [Solved-5 Solutions] Looping through the content of a file in Bash - ubuntu - red hat - debian - linux server - linux pc



Linux - Problem :

How to iterate through each line of a text file with Bash ?

Linux - Solution 1:

while read p; do
  echo $p
done <peptides.txt
click below button to copy the code. By - Linux tutorial - team

If the loop body may read from standard input, you can open the file using a different file descriptor:

while read -u 10 p; do
  ...
done 10<peptides.txt
click below button to copy the code. By - Linux tutorial - team

Here, 10 is just an arbitrary number (different from 0, 1, 2).

Linux - Solution 2:

cat peptides.txt | while read line
do
   # do something with $line here
done
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 3:

Option 1: While loop: Single line at a time: Input redirection

#!/bin/bash
filename='peptides.txt'
echo Start
while read p; do 
    echo $p
done < $filename
click below button to copy the code. By - Linux tutorial - team

Option 2: While loop: Single line at a time:

Open the file, read from a file descriptor.

#!/bin/bash
filename='peptides.txt'
exec 4<$filename
echo Start
while read -u4 p ; do
    echo $p
done
click below button to copy the code. By - Linux tutorial - team

Option 3: For loop: Read file into single variable and parse.

  • This syntax will parse "lines" based on any white space between the tokens.
  • This still works because the given input file lines are single work tokens.
  • If there were more than one token per line, then this method would not work as well.
  • Also, reading the full file into a single variable is not a good strategy for large files.
#!/bin/bash
filename='peptides.txt'
filelines=`cat $filename`
echo Start
for line in $filelines ; do
    echo $line
done
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 4:

Use a while loop, like this:

while IFS= read -r line; do
   echo "$line"
done <file
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 5:

#!/bin/bash
#
# Change the file name from "test" to desired input file 
# (The comments in bash are prefixed with #'s)
for x in $(cat test.txt)
do
    echo $x
done
click below button to copy the code. By - Linux tutorial - team

Related Searches to - linux - linux tutorial - Looping through the content of a file in Bash