Reading a file line by line from BASH

bash-logo-webTo 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

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

Option 2

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:

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

Spanish video

YouTube video

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.