If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > Unix Shell Scripts > Reading a File Line By Line

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 01-20-04, 15:02
Darren[UoW] Darren[UoW] is offline
Registered User
 
Join Date: Jan 2004
Posts: 1
Reading a File Line By Line

I am using the following code to read line by line from a file, however my problem is that $value=0 at the end of the loop possibly because bash has created a subshell for the loop or something similar. How can I solve this.


value=0;

while read line
do
value=`expr $value + 1`;
echo $value;
done < "myfile"

echo $value;


Note: This example just counts the number of lines, I actually desire to do more complex processing than this though, so 'wc' is not an alternative.


Thanks Darren.
Reply With Quote
  #2 (permalink)  
Old 01-20-04, 17:37
fla5do fla5do is offline
Registered User
 
Join Date: Oct 2003
Location: Germany
Posts: 138
Hi Daren,
use awk for complex processing.
for example :


value=`cat myfile | awk ' BEGIN { FS=":"}
{
# here jou can use all complex processing from awk
# for loops / while loops / if then else / etc.
x=x+1
} END {
print x
}'`
echo $value #give the same output as your script

# what do you want to do
# tell it by example
__________________
Greetings from germany
Peter F.

Last edited by fla5do; 01-20-04 at 18:17.
Reply With Quote
  #3 (permalink)  
Old 01-21-04, 03:57
chillies chillies is offline
Registered User
 
Join Date: Jul 2003
Location: Edinburgh
Posts: 35
Re: Reading a File Line By Line

In your example $value should be the number of lines in "myfile". Check that the file is not empty, or that you've typoed somewhere. Which version of bash? Which platform?

Backquotes do start a subshell, with the performance overhead that implies. You could use the shell's integer arithmetic funtions with the "let" command e.g.
let value=$value+1
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On