954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Help in assignment shell

in shell scripting
let say a variable

first="abcd:efgh"

how do I find the index of : if its even possible
thanks

War_Archer
Newbie Poster
5 posts since May 2010
Reputation Points: 10
Solved Threads: 0
 

There are a lot of ways. First question: Why do you want the index? Stop and think about what you want to use it for, and maybe you can go directly to the need instead of by steps. Do you want everything to the left (or right) of the ':'?
leftpart=$(echo $first | cut -f 1 -d ':') rightpart=$(echo $first | cut -f 2 -d ':')

Do you want to split it into pieces and handle them individually?

for part in $(echo $first|tr ':' ' ') ; do
  echo $part
done

You can also try to use the ternary operator if you use a recent bash shell, but I've been having trouble finding a good example. I also often use awk (gawk for the gnu version) which is pretty arcane, but quite useful. Or step up to Python or perl?

griswolf
Veteran Poster
1,165 posts since Apr 2010
Reputation Points: 344
Solved Threads: 256
 

Thanks thats exactly what I was looking for

War_Archer
Newbie Poster
5 posts since May 2010
Reputation Points: 10
Solved Threads: 0
 

in shell scripting let say a variable

first="abcd:efgh"

how do I find the index of : if its even possible thanks

[indent]
There's no need for any external command; the shell can do it internally:

index()
{
    case $1 in
        *$2*)
           idx=${1%%$2*}
           echo $(( ${#idx} + 1 ))
           ;;
        *) echo 0 ;;
    esac
}


Sample run:

$ first="abcd:efgh"
$ index "$first" ":"
5
$ index "$first" "c"
3
$

[/indent]

cfajohnson
Junior Poster
196 posts since Dec 2008
Reputation Points: 25
Solved Threads: 23
 

Hiiii,
Can u help me out..I want to make some tables and give some querries in mysql. And I want to automate this... So can someone help me to write a script which will do all this....
It should open mysql....put in the password and must be able to type something in it.

akand
Newbie Poster
20 posts since Jun 2010
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: