Bash – Reading File

Background

Now that we are able to run Bash on a Windows machine, it is even more reason to be aware of it.

 

Read a File

Tradition

Reading a file usually follows the following sequence:-

  1. Open File for reading
  2. Read line
  3. If EOF exit
    • Process Read Line
    • Read Next
  4. Return to EOF check

 

 

Datafile

Let us use a simple datafile


John Smith; jsmith801@yahoo.com
Larry Holmes; lholmes945@msn.com
Paul Young; paulyoung@me.com
Grant Hill; ghill@excite.com
Tamia; tamia@att.com

Bash

Introduction

In Unix/Bash, everything is a file and so there is no explicit open/close file

 

Outline

  1. Specify Scripting Language
    • Bash
      • #!/bin/bash
  2. Data file name
    • Hardcode as datafile/blackbook.txt
      • File is located in the datafile sub-folder
      • File Name is blackbook.txt
  3. Initialize variables
    • Global
      • Internal File Separator ( IFS )
        • Semi-Colon ( ; )
    • Local Variables
      • lineNumber
  4. Validation
    • File Exists?
      • if [ ! -f “$filedata” ]
  5. Read File
    • Read fullname & emailAddress
      • while read -r fullname emailAddress
  6. Increment line number
    • lineNumber=$((lineNumber+1))
  7. Print Detail
    • Use printf to display formatted output
  8. Done at EOF
    • done < “$filedata”

Code


#!/bin/bash

#set name of datafile
filedata="datafile/blackbook.txt"

#set the Internal File Separator
#in our case set to semi colon (;)
IFS=';'

#set line number
lineNumber=0

#does file exist
#https://linuxize.com/post/bash-check-if-file-exists/
if [ ! -f "$filedata" ]; then

    printf "file (%s) does not exist! \n" $filedata

    exit

fi



printf "%3s   %-15s %-15s  %-15s \n" "###" "First Name"  "Last Name"   "Email"

printf "%3s   %-15s %-15s  %-15s \n" "---" "----------"  "---------"   "-----"

#read file
#read fullname, emailAddress

while read -r fullname emailAddress
do

   #increment line number
   lineNumber=$((lineNumber+1))

   # using the awk command the first column
   firstname=$(echo "$fullname" | awk -F ' ' '{print $1}' )

   # using the awk command get the second column
   lastname=$(echo "$fullname"  | awk -F ' ' '{print $2}' )

   #display read line
   printf "%3d)  %-15s %-15s %-15s \n" "$lineNumber" "$firstname" "$lastname" "$emailAddress"

#we are done at EOF
done < "$filedata"




Output

 

Source Code Control

GitHub

Gist

readfile.sh

Link

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s