Skip to main content

Read a File line by line in Shell

I've used a few techniques for this kind of reading but gets failed until I've read this fine blog .
http://www.bashguru.com/2010/05/how-to-read-file-line-by-line-in-shell.html
this helps a lot and i have developed a trick for me.
Refer to the following example to examine the script :


#!/bin/bash
#SCRIPT:  method2.sh
#PURPOSE: Process a file line by line with redirected while-read loop.

FILENAME=$1
count=0

while read LINE
do
      let count++
      echo "$count $LINE"

done < $FILENAME

echo -e "\nTotal $count Lines read"

I have passed the file in the end of the loop so i didn't need 
to use pipe that is why i process the file in fastest manner and gives 
the required output in a quick manner.

However i can use one more thing the File Descriptors.
The File Descriptors are similar to the normal file pointers however in 
more analogue way.If you have used C then you will have familier with the 
the default file openers in C "stdin","stdout" and "stderror" 
and each of them is assigned with a file descriptor respectivly 0,1 and 2.
For opening additional files there are a few more descriptors from 3 to 9 
depending on your OS. So come to the point, if you want to read your file 
from standard input usually known as stdin among developers you need to 
change the default input from 0 to any other descriptor like this:

exec 3<&0

it will change the defdault stdin descriptor from 0 to 3 and you need to 
follow one more step to complete the task is:

exec 0<$filename
 
and its done. Now use the below given script to acomplish your job.

#!/bin/bash
#SCRIPT:  method3.sh
#PURPOSE: Process a file line by line with while read LINE Using
#File Descriptors

FILENAME=$1
count0=
exec 3<&0
exec 0< $FILENAME

while read LINE
do
        let count++
        echo "$count $LINE"
done

exec 0<&3
echo -e "\nTotal $count Lines read"

For more information refer to the given blog and use man pages for command 
information.

Comments

Popular posts

Using Flash in your HTML

Edit your Publish settings for Flash SWFs and HTML to reflect how you want your Flash SWF to appear in your web page. Export your Flash movie as HTML. Locate your HTML file on your computer, right-click, and select "Open With". Choose either NotePad or another text editor. Copy the source code from the HTML file. Paste it into your web page's source code in the appropriate location where you want your SWF file to display. Edit the file path to reflect the location of the SWF file on your web server, and upload both your HTML and SWF file to the appropriate directories on your server. ( Note:  this also applies if you're using PHP, JSP, ASP, CGI, or other web page extensions.) Your code should look something like this: <OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="320" HEIGHT="240" id="You...

Enter your email address: