How to extract a substring matching a pattern from a Unix shell variable

I am relatively new to Unix shell scripts. Here is my problem. I used this script ...

isql -S$server -D$database -U$userID -P$password << EOF > $test exec MY_STORED_PROC go EOF echo $test 

To generate this result ...

 Msg 257, Level 16, State 1: Server 'MY_SERVER', Procedure 'MY_STORED_PROC': Implicit conversion from datatype 'VARCHAR' to 'NUMERIC' is not allowed. Use the CONVERT function to run this query. (1 row affected) (return status = 257) 

Instead of echoing isql, I would like to extract "257" and paste it into another variable so that I can return 257 from the script. I think some sed or grep command will do this, but I don't know where to start.

Any suggestions?

+4
source share
2 answers

bash can strip parts from the contents of shell variables.

${parameter#pattern} returns the value of parameter $ without the part at the beginning that matches pattern .

${parameter%pattern} returns the value of parameter $ without the part at the end that matches pattern .

I think there is a better way to do this, but it should work. So you can combine this in:

 % strip the part before the value: test=${test#Msg } % strip the part after the value: test=${test%, Level*} echo $test 

If you are interested in the part (return status = xxx) , this will be:

 result=${test#*(result status = } result=${result%)*} echo $result 

The relevant section in the bash man page is โ€œParameter Extensionโ€.

+14
source

Here's a quick and dirty hack for you, although you really should start learning this stuff yourself:

  RC = `tail -1 $ test | sed 's / (return status = \ ([0-9] \ + \)) / \ 1 /' '
+2
source

All Articles