Thursday, July 4, 2019

How to loop through the content of a file in Bash [SOLVED]

I saw that many people face the problem to loop through the file content in Bash.
I have some solutions for this. There are many ways through you can achieve this.
You can choose the one which suits you.

Option No.1
while IFS="" read -r p || [ -n "$p" ]
do
  printf '%s\n' "$p"
done < peptides.txt
If your file has leading whitespace, interpretting backslash sequences, and you want to skip the trailing line then above solution is for you.


Option No. 2
#!/bin/bash
filename='peptides.txt'
echo Start
while read p; do 
    echo $p
done < $filename
above option is a while loop option. Single line at a time. Input redirection.


Option No. 3
#!/bin/bash
filename='peptides.txt'
exec 4<$filename
echo Start
while read -u4 p ; do
    echo $p
done
Above one is also in while loop: Single line at a time:
Open the file, read from a file descriptor (in this case file descriptor #4).


Option No. 4 
while IFS= read -r line; do
   echo "$line"
done <file
Above option is with simple while loop. You need to set the IFS properly, otherwise you will loose the indentation. Also always use the -r option with read. NEVER EVER use the for loop for reading lines. 


I hope these options are helpful for you. ðŸ˜ƒ

Let me know your feedback!

Thanks for reading!
Amit




Tags:
Read the content of file through bash, loop through content of file bash, bash read file



4 comments: