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

    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.


    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.

  2. #2
    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
    Last edited by fla5do; 01-20-04 at 19:17.
    Greetings from germany
    Peter F.

  3. #3
    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

Posting Permissions

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