Register
It is currently Tue Sep 23, 2014 6:24 pm

function to get numerical position of a character


All times are UTC - 6 hours


Post new topic Reply to topic  [ 2 posts ] 
Author Message
 PostPosted: Sat Jul 30, 2005 12:18 am   
Site Admin

Joined: Tue May 17, 2005 7:31 pm
Posts: 251
Location: Georgia
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 :)


Top
 Profile  
 PostPosted: Fri Nov 28, 2008 10:40 pm   

Joined: Fri Nov 28, 2008 10:32 pm
Posts: 3
What about:
Code:
while read a b; do  ## this will aslo work if you have lines of the form:  "name=Bob any-more info-on this line"
  key=${a%=*}
  val=${a#*=}
  echo "$key = $val"
done


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 2 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP