Reading a file line by line from BASH

bash-logo-web

To read a file line by line from BASH you can use one of the following options:

  1. While, read, operator <
  2. cat, while, read
  3. AWK

For example, if we have the following file:

imperdiet.nec.leo@etmalesuadafames.net
molestie.in.tempus@nuncQuisque.edu
a.sollicitudin.orci@ut.edu
lorem.Donec.elementum@arcuNunc.ca
et.rutrum.eu@nisidictumaugue.ca
augue@Cumsociis.co.uk
adipiscing@convallisestvitae.com
Nunc.sed.orci@rhoncusDonecest.org
pede@tempuslorem.net
imperdiet@InloremDonec.ca

Option 1

Fork me on Github
while read line; do echo "Sending email to $line"; done < emails.txt

Option 2

Fork me on Github
cat emails.txt |while read line; do  echo "Sending email to $line"; done

Option 3

I suggest AWK if the file has more than one column since AWK allows to specify columns separator, if we have the following file:

Sybil|arcu@dolordolor.ca
Neville|euismod@semperNam.co.uk
Sean|In.lorem.Donec@tinciduntaliquamarcu.edu

then we can type:

Fork me on Github
awk -F'|' '{email=$1" <"$2">"} {print "Sending email to "email;}' emails.txt

Further readings

  • bash -c "while help"
  • bash -c "help read"
  • man cat
  • man awk



Leave a Comment

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