string split, bash and IFS
unga888 at yahoo.com
Mon Aug 25 14:10:56 UTC 2008
--- On Mon, 8/25/08, Barry Byrne <barry.byrne at wbtsystems.com> wrote:
> From: Barry Byrne <barry.byrne at wbtsystems.com>
> Subject: RE: string split, bash and IFS
> To: unga888 at yahoo.com, freebsd-questions at freebsd.org
> Date: Monday, August 25, 2008, 7:54 PM
> > -----Original Message-----
> > From: owner-freebsd-questions at freebsd.org
> > [mailto:owner-freebsd-questions at freebsd.org] On Behalf
> Of Unga
> > Sent: 25 August 2008 10:40
> > To: freebsd-questions at freebsd.org
> > Subject: string split, bash and IFS
> > How to use bash and IFS to split a string?
> > eg.
> > $string = "Name:Surname:10"
> > IFS=:
> > echo "$string" | read name surname age
> > This does not work for some reason. The read does not
> > name, surname and age variables. Any idea why?
> > Appreciate your reply.
> d-questions-unsubscribe at freebsd.org"
> I think your problem is that each element of the pipeline
> runs in a separate
> process, so has no access to the variables from other
> processes. You could
> try something like:
> echo "Name:Surname:10" | ( IFS=: ; read name
> surname age ; echo $surname)
Thanks for the reply. Your statement prints the Surname but the variable $surname disappear after that and not available for further processing.
I'm referring to two sources for this:
1. Learning the bash shell, 2nd Edition. O'Reilly publishers
Where on page 170, under read section
The basic syntax is:
read var1 var2...
This statement takes a line from the standard input and breaks it down into words delimited by any of the characters in the value of the environment variable IFS. The words are assigned to variables var1, var2, etc.
It looks like it works for others but here on FreeBSD 7.0, bash 3.2.33(0)-release, I find it difficult to get this syntax to work.
> Also, probably a typo - but you're assignment of string
> in the first line
> should omit the $ sign.
Yes, sure is a typo.
More information about the freebsd-questions