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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find a value in a variable

Status
Not open for further replies.

alhassani54

Programmer
Aug 1, 2002
27
0
0
GB
I have a variable which contains a delimiter and the value between the delimiter can be various.

i.e.
a=1234~56789~asdfgt~jfdhjrhtj~nvcnvcn
or it could be
a=12~q~jjjjjjj~erorioe~90~9824

A script to return a value for a specific delimiter.
Script name “retval”

By entering :-
retval “12~q~jjjjjjj~erorioe~90~9824” “~” 1 3
This will return:-
12~q~jjjjjjj
or by entering:-
retval “12~q~jjjjjjj~erorioe~90~9824” “~” 4 5
The script will return:-
erorioe~90

Any help will be appreciated.

Thanks
 

retval “12~q~jjjjjjj~erorioe~90~9824” “~” 4 5
^ ^ ^ ^
$1 $2 $3 $4
assuming:
$1 is the string
$2 is the trailer, ~ is a special char, try an other
$3 is start pos
$4 is end pos

something like:

echo $1 | cut -d$2 -f$3-$4

should work
-----------
when they don't ask you anymore, where they are come from, and they don't tell you anymore, where they go ... you'r getting older !
 
If you would like to keep everything is a shell context and avoid the outside use of cut to enhance performance you can do it this way in bash ksh zsh and newer sh(posix) shells:


#!/bin/bash

parse()
{
count=0
var_in=$1
IFS='~'
for value in $var_in
do

arrayval[$count]=$value
((count = count + 1))
done
}

showval()
{
arrayval=()
parse $a
for args in $*
do
if [ "$args" -le ${#arrayval[*]} ]
then
echo ${arrayval[$args]}
fi
done
}

a=1234~56789~jfdhjrhtj~nvcnvcn

#call from inside the script

showval 0 2

#If you want it to call it from outside just use the following:

# showval $*
# end script


Keep in mind that the way I've done it here is with a static variable "a". You could make the functions work with any variable fed to it.

Also, I used a shell array that begins counting at 0 for its subscripts. You could write a bit of shell code that would automattically subtract 1 from any value input to the command.

I did put in a check to make sure that the value input did not exceed the array bounds, but it just skips the step and doesn't give a friendly error message or log anything.

This helps if you have a huge text database to go through. If you use subshells as you do when you use an outside utility performance can degrade signficantly.

By creating a set of shell functions that do this sort of thing you create the basis of a great text/shell dbms system.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top