Link to home
Start Free TrialLog in
Avatar of serjosh
serjosh

asked on

Pull a string out of a string in a shell script

I have a linux shell script that contains a variable with a very long string in it.  I need to pull a string out of that very long string.  The string will start with "oct 19" and end with "blahblah".  But the number of characters in between will vary.  How do I extract the string?
Avatar of Tyler Laczko
Tyler Laczko
Flag of Canada image

$mystring = "long string oct aklsdfgklajg akgjasdgjka blah asdgasdg";
//split into 2 parts
@s_array1 = split("oct", $mystring);
split into 2 parts
@s_array2 = split("oct", @s_array1[1]);

print @s_array2[0];
$mystring = "long string oct aklsdfgklajg akgjasdgjka blah asdgasdg";
//split into 2 parts
@s_array1 = split("oct 19", $mystring);
split into 2 parts
@s_array2 = split("blahblah", @s_array1[1]);

print @s_array2[0];
$mystring = "long string oct aklsdfgklajg akgjasdgjka blah asdgasdg";
//split into 2 parts
@s_array1 = split("oct 19", $mystring);
//split into 2 parts
@s_array2 = split("blahblah", @s_array1[1]);

print @s_array2[0];
Avatar of serjosh
serjosh

ASKER

Professionalcomputersolutions,
I get all kinds of errors in my shell script after I put your code into it.

./Cgrep.sh: line 11: =: command not found
./Cgrep.sh: line 12: //split: No such file or directory
./Cgrep.sh: line 13: syntax error near unexpected token `('
./Cgrep.sh: line 13: `@s_array1 = split("oct 19", $mystring);'
lol

dont just copy and paste my code.

look at it and read it then write your own code.

mine is just an algorithm

Declare your long string
Split the string into 2 parts
you will now have 2 strings 1st is garbage 2nd is the start of what you want to the very end
split the 2nd string into 2 parts
you will have 2 more strings the first contains the info you want the second is garbage

use the string in pos 0 of the second array.
ASKER CERTIFIED SOLUTION
Avatar of Tintin
Tintin

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of serjosh

ASKER

I guess the 'split' function is the part that is confusing me.  This is a bash shell script.  Can the unix split command be used the way you are saying?  It seems it's used to split files not strings?  I get errors every time i try to use it.  perhaps you could give me a little more verbose description of how I can accomplish this?  Sorry for my confusion =P
professionalcomputersolutions gave you Perl code, not shell script.

Just use my grep solution.  Much easier :)
Avatar of serjosh

ASKER

That seems to have done it, thanks!