[clug] easier way to use IFS in bash?
David Tulloh
david.tulloh at infaze.com.au
Tue Aug 10 01:46:00 GMT 2004
I'm not sure if you would consider this cheating, but personally I would
use awk:
pos=0 # or whatever you are after
res=`echo "$var" | awk -v pos=$pos '{print $(pos+1)}'`
David
Steven Hanley wrote:
> All
>
> Looking at using word splitting in bash, say I have a string and I want to
> return the 1st word before a whitespace character or the third word or
> something.
>
> The below works
>
> ******
> #! /bin/bash
>
> function IFS_word_at_pos () {
> local str1=$1
> local pos=$2
> local i=0
> for word in $str1 ; do
> if [ $i -eq $pos ] ; then
> echo $word
> fi
> i=$(($i+1))
> done
> }
> ******
>
> var="zero one two three four five six seven"
>
> res=`IFS_word_at_pos "$var" 0`
> echo $res
>
> However it seems long and ugly to have to use a for loop in order to spluit
> up some words.
>
> There are the glob based string expansion things you can use such as
>
> res=${var% *}
>
> which would return the first bunch of text before a space in the variable
> $var
>
> However it is not generic to whitespace, obays the glob rules and also is
> not really what I would be after.
>
> Does anyone have ideas of how to do this in a cleaner manner using the IFS
> whitespace stuff?
>
> See You
> Steve
>
More information about the linux
mailing list