This script will return the position of a character (or string of characters) in a string. With that information you can better manipulate strings for your own amusement
For instance...
Let's say you have a string:
Name=Bob
All you need is:
Bob
The easiest way I can figure to get Bob is to take that string from the right side using the positional parameters in a variable (i.e. ${String:StartPosition:Length} )
So you need a start position...
Code:
function inStr
{
searchFor="$1";
lenOf=${#searchFor};
searchIn="$2";
for (( i=0; i < ${#searchIn}; i++ ))
do
if [[ "${searchIn:$i:$lenOf}" = "$searchFor" ]]
then
return $i
fi
done
echo "$searchFor is not in $searchIn"
}
What the above does is loop through the String provided looking for a match. You would call it like:
Code:
string="Name=Bob"
inStr "=" "$string"
val=$?
At this point, val=4. So if we wanted the word Bob, we would do:
Code:
newString=${string:${val}+1}
newString equals Bob
Since the start position is val + 1 (the first letter after the = ).
This function is super handy for things like... configuration files.
Atleast configuration files with the format:
Object=Value
To read in a configuration file, I would (and do) do this:
Code:
until ! read file
do
InStr "=" "$file"
pos=$?
object=${file:0:${pos}}
value=${file:${pos}+1}
echo "Object: $object :: Value: $value"
done < "/path/to/config.file"
Hope this helps someone out there
