[clug] easier way to use IFS in bash?
Steven Hanley
sjh at svana.org
Tue Aug 10 01:21:43 GMT 2004
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
--
sjh at wibble.net http://svana.org/sjh
You are subtle as a window pane standing in my view
but I will wait for it to rain so that I can see you
Anticipate - Ani
More information about the linux
mailing list