Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I'm trying parse the text of a string in bash which I then can throw a case selection at, but I'm having the biggest trouble trying to figure how to do it. In VB I know its real easy like

someString = "Hey there"
Select Case Mid(someString,1,5)
 Case "Hey t" 'Do something
 Case "Go aw" 'Do something else
 Case 'Else
  'String is unrecognized
End Select

I can't seem to find anything that shows how I can do a string manipulation function which is equivalent to the Mid function. Do I use sed, I don't believe I can use awk or cut since I'm not trying to trim a string based upon a pattern, but surely it has to be just as simple in Unix.

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

I'm not sure I understand your question, since I think 'cut' will work just as you want it to.

someString="Hey there"

case `echo $someString | cut -c1-5` in
    "Hey t") echo Do something ;;
    "Go aw") echo Do something else ;;
    *) echo String is unrecognized ;;
esac
share|improve this answer
    
Honestly I liked yours best as I think it's easier to read, but for some reason the code is not work when executed in a bash script. I always get a "String is unrecognized" result. –  mrTomahawk May 6 '09 at 10:44
    
I just realized that I was using single quote vice backquotes around the case statement which was causing my issue. I also just learned that your answer would also work i the other shells, so I think yours is actually better. –  mrTomahawk May 6 '09 at 15:05
add comment
someString="Hey there"
case "${someString:0:5}" in
    "Hey t" ) echo Do something ;;
    "Go aw" ) echo Do something else ;;
    * ) 	  echo unrecognized  ;;
 esac

This could also easily be done with an if, elif, else. The ${someString:0:5} is parameter expansion. Learn more from it's section in the bash manual, and also from Gregs Bash FAQ #73.

Notice the other answer that uses cut. Both will work, however Parameter expansion is faster because its builtin to bash and considered better code. cut would be good for cutting across multiple lines of text.

share|improve this answer
    
+1 for giving what I think is the correct answer: do not toss in another 'cut'. Bash is perfectly able to do substrings by itself. –  wzzrd Jun 22 '09 at 12:05
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.