Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2004

    Unanswered: 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.


    while read line
    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.

  2. #2
    Join Date
    Oct 2003
    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.
    } END {
    print x
    echo $value #give the same output as your script

    # what do you want to do
    # tell it by example
    Last edited by fla5do; 01-20-04 at 19:17.
    Greetings from germany
    Peter F.

  3. #3
    Join Date
    Jul 2003

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts