Rei*_* SE 0 string ksh substring solaris-10
如果我有这样的字符串:
The important variable=123 the rest is not important.
Run Code Online (Sandbox Code Playgroud)
我想在ksh中提取"123"部分.
到目前为止,我尝试过:
print awk ' {substr($line, 20) }' | read TEMP_VALUE
Run Code Online (Sandbox Code Playgroud)
(这20部分只是暂时的,直到我弄清楚如何提取字符串的起始位置.)
但是,这只是打印awk ' {substr($line, 20) }' | read TEMP_VALUE(虽然这种格式也有这样的代码工作:print ${line} | awk '{print $1}' | read SINGLE_FILE).
我错过了一个简单的命令来执行此操作(即其他语言)吗?
运行Solaris 10.
小智 6
我们是否假设在我们想要的部分总是相同的长度之前是什么?然后:
echo ${variable:23:3}
Run Code Online (Sandbox Code Playgroud)
或者我们假设我们可以使用=符号的位置和123之后的空格作为分隔符?我们知道它总是3个字符吗?如果你知道你想要的部分以=和3个字符开头:
variable=${variable#*=} # strip off everything up to and including the '=' sign
${variable:0:3} # get the next three characters.
Run Code Online (Sandbox Code Playgroud)
真的需要有关变量长度和结构的更多信息.
如果你知道的是你想要跟随=下一个空间的任何内容,那么Glenn的解决方案看起来是正确的.
您的命令失败有多种原因:您需要类似的东西
TEMP_VALUE=$(print "$line" | awk '...')
Run Code Online (Sandbox Code Playgroud)
您可以使用ksh参数扩展:
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
Run Code Online (Sandbox Code Playgroud)
在ksh手册页中查找"参数替换".