String processing in shell

How do I process search/replace strings (something like using substr in perl) in a shell script (bash, ksh, etc.). Here's what I want to do:
   - Given a string, I want to:
          a) find a substring
          b) extract the previous 8B in front of it

For example (spaces added only to flag substring and desired match string; there will be no spaces in the "real" string), given the string (hex characters only):
          AB 24BDF5ABED8CA734 09C8A78348C87A6B DFE2334ADAB342097A87F6DE7A5B78C678EF876AB
   I will be given a substring (this will be known): 09C8A78348C87A6B
   and want to extract the previous 8 bytes (16 characters - 24BDF5ABED8CA734) using only shell commands (this is the unknown I wish to find).

Can this be done? I've tried using
    expr index "$string" $substring
    ${string:position:length}
    ${string:position}
to no avail... the first of these three expressions shows the most promise, but the "$substring" matches only by character and not the entire substring - e.g. 0 or 9 or C or 8 or A ...etc. will match. I can do this in Perl, but my environment requires I only use shell.
LVL 1
mikestanAsked:
Who is Participating?
 
Peter KwanAnalyst ProgrammerCommented:
You may use awk to do the work for you:

STR=<your string>
echo $STR | awk '{
   s=index($0, "09C8A78348C87A6B");
   if (s != 0) {
      print substr($0, s-16, 16);
   }
}'
0
 
sunnycoderCommented:
$ echo AB24BDF5ABED8CA73409C8A78348C87A6BDFE2334ADAB342097A87F6DE7A5B78C678EF876AB | sed 's:.*\(................\)09C8A78348C87A6B.*:\1:'
24BDF5ABED8CA734
0
 
mikestanAuthor Commented:
Thanks to you both! I was also trying something like this but also thought of making the "09C8A78348C87A6B" into a shell variable (i.e. known=09C8A78348C87A6B read in from a file or user prompt). This will work for now and will figure out how to program in more advanced features later.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.