Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

split string

Status
Not open for further replies.

krava

Programmer
Jun 4, 2007
48
YU
Hi

I would like to have a function in .bashrc that would split a string into substrings (according to given separator) and to return a given substring. Something like:

function splitString() {
#echo $1;
awk -v name=$1 -v sep=$2 -v field=$3 'BEGIN{split(name,a,sep); print a[field]}'
return a[$3]
}

usage would be like:

splitString "peca_is_stupid" "_" 3

with result:

"stupid"

How to return "stupid" from this function to be further usable in the main script that use splitString() function?

thanx
peca

 
Something like this ?
Code:
splitString() {
#Usage: field=`splitString string separator fieldnum`
 awk -v name=$1 -v sep=$2 -v field=$3 'BEGIN{split(name,a,sep); print a[field]}'
}

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
thanx PHV,

Does it mean that I can not return values with return a[$3]? I mean, what if I have:

function splitString() {
echo $1;
awk -v name=$1 -v sep=$2 -v field=$3 'BEGIN{split name,a,sep); print a[field]}'
}

Then the usage you proposed:

#Usage: field=`splitString string separator fieldnum`

will assign both $1 and a[field] to the variable 'field' above and I dont want that
 
and I dont want that
So, get rid of the echo in your function !
 
this is just a simple example ... in more complex prog I can not always get rid of every echos. true?
 
Typed, untested:
Code:
splitString() {
#Usage: splitString string separator fieldnum fieldvar
 [ $# -eq 4 ] || return
 x=$4
 eval $x=\"$(awk -v name=$1 -v sep=$2 -v field=$3 'BEGIN{split(name,a,sep);print a[field]}')\"
}
For testing:
splitString "peca_is_stupid" "_" 3 result
echo "result='$result'"

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top