Re: [SLUG] Bash Problem - SOLVED

From: Timothy L. Jones (tim@timjones.com)
Date: Thu Aug 07 2003 - 08:19:29 EDT


You might also find something like this useful. (I know it's already solved,
but this is a wholly different approach)

        cat file | while read line
        do
           mystuff $line
        done

I have also seen scripts where 'read' will parse a IFS-delimited line into
multiple variables for you. Example: CSV (comma-separated values) file:

        Jones,Tim,123-12-1234
        Foster,Paul,234-23-2345

shell script to re-arrange the fields (w/o commas)

        export IFS=,
        cat text.csv | while read lname fname ssn
        do
           echo $ssn $fname $lname
        done

Just tried it out, tastes great, less filling!

If there are more than 3 fields in this example, all the extra fields will be
assigned to the last variable (ssn in my example). If there aren't enough
fields, the unused ones will be blank.

You could combine both methods if you really wanted:

        export IFS=,
        cat text.csv | while read line
        do
                echo new record has `echo $line | wc -w | bc` fields
                                # bc strips of wc's extra spaces
                for field in $line
                do
                        echo field: $field
                done
        done

tlj

El Jue 07 Ago 2003 02:07 AM, Paul M Foster escribió:
> On Thu, Aug 07, 2003 at 12:38:49AM -0400, Paul M Foster wrote:
> > Within a bash script, I'm trying to feed each line of a file into a
> > variable, to wit:
> >
> > for line in `cat file`
> > do
> > do_whatever
> > done
> >
> > At the end of this operation, I want the $line variable to equal the
> > contents of a single line in the file. The problem is that the shell
> > breaks the line into _words_ if there are any spaces, tabs or newlines
> > in it. I understand why. It's because of the value of the IFS shell
> > variable. To get around this, I want to set the IFS variable to be
> > _only_ the newline. But I can't find a way to do it. The following do
> > not work:
> >
> > IFS=
> >
> > IFS=\n
> > IFS='\n'
> > IFS="\n"
>
> The answer (to set IFS to only a newline) is:
>
> IFS='
> '
>
> Paul
> -----------------------------------------------------------------------
> This list is provided as an unmoderated internet service by Networked
> Knowledge Systems (NKS). Views and opinions expressed in messages
> posted are those of the author and do not necessarily reflect the
> official policy or position of NKS or any of its employees.

-----------------------------------------------------------------------
This list is provided as an unmoderated internet service by Networked
Knowledge Systems (NKS). Views and opinions expressed in messages
posted are those of the author and do not necessarily reflect the
official policy or position of NKS or any of its employees.



This archive was generated by hypermail 2.1.3 : Fri Aug 01 2014 - 16:13:22 EDT