Search code examples
stringsubstringkshsolaris-10

How can I extract a substring after a certain string in ksh?


If I have a string like this:

The important variable=123 the rest is not important.

I want to extract the "123" part in ksh.

So far I have tried:

print awk ' {substr($line, 20) }' | read TEMP_VALUE

(This 20 part is just temporary, until I work out how to extract the start position of a string.)

But this just prints awk ' {substr($line, 20) }' | read TEMP_VALUE (though this format does work with code like this: print ${line} | awk '{print $1}' | read SINGLE_FILE).

Am I missing a simple command to do this (that is in other languages)?

Running Solaris 10.


Solution

  • Your command is failing for multiple reasons: you need something like

    TEMP_VALUE=$(print "$line" | awk '...')
    

    You can use ksh parameter expansion though:

    line="The important variable=123 the rest is not important."
    tmp=${line#*=}   # strip off the stuff up to and including the equal sign
    num=${tmp%% *}   # strip off a space and all following the first space
    print $num       # ==> 123
    

    Look for "parameter substitution" in the ksh man page.