[svlug] looping through a file line by line

Tim Flagg timf at linuxmigration.com
Mon Apr 21 17:03:32 PDT 2003


John,

> I have a file that I want to split up line by line and I can't seem to do
> this properly. Googling isn't exactly helpful - it turns up many results,
> all with the search terms, but the S/N is pretty low.
> 
> Anyway, how should I go abuot doing this? Using 'for' and eitehr cut or
> cat gives me each word.

Here is a shell script named "linebyline.sh" that will let you perform
an operation on each line:

    #!/bin/bash -f
    while true
    do
        read line
        if [ $? -eq 0 ]
        then
            echo line is $line about to be operated on...
        else
            echo End of file.
            exit 0
        fi
    done

You can run it with standard input redirected from the file
you want to operate on, e.g.:

    linebyline.sh < inputfile

If you need somthing fancier, I'd recommend awk, which can do
almost anything and is lots of fun.  Then again, there's python,
which is even more fun and more powerful than awk in most cases.

Tim




More information about the svlug mailing list