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.
Your command is failing for multiple reasons: you need something like
You can use ksh parameter expansion though:
Look for "parameter substitution" in the ksh man page.
Using sed, the inline editor:
sed matches the string in x:
. s/ substitute command and start of test regex - .* matches anything, any number of times from zero on - important variable= matches exactly " important variable=" including the preceding space - (\d\d\d) the three \d's match 3 digits, the enclosing escaped parenthesis enable back referencing the 3 digits actually matched - .* a space and .* (anything) again - / end of test regex - \1 substitution string
The matched text (all of $x, in fact) will be replaced by the substitution string, the 3 digits found in $x.
Are we assuming what ever is before the part we want is always the same length? Then:
Or are we assuming we can use the position of the
=
sign and the space after the 123 as delimiters? Do we know it's always 3 characters? If you know the part you want begins with the=
and is 3 characters long:Really need more info regarding the length and structure of the variable.
If all you know is you want whatever follows the
=
up to the next space, then Glenn's solution looks correct.(Sorry, coming along a bit late to this one!) How are you intending to identify that "123" is the part to extract? If the criterion is simply that it is the first field after the "=" sign you can do:
echo "The important variable=123 the rest is not important."|cut -f2 -d=|cut -f1 -d " "
I have used this in the past.
echo "var=123" | awk 'BEGIN{FS="="} {print $2}'
Then you can also grab the variable if you need with $1 symbol.