如何使用bash解析字符串以获取数字 [英] How can I parse a string using bash to get a number
问题描述
我有以下字符串:
PR-1769|7bb12d4152a497cef491e0a1088b3984ad92972f|jaga|
如何使用bash解析上面的字符串,以便获得 1769
?
How can I parse the string above using bash so that I get the 1769
?
另外,如何使用bash获取最后一个字符串 jaga
?
Also, how do I get the last string jaga
using bash?
推荐答案
这里不需要 grep
:bash具有内置的正则表达式支持,非常使用效率比启动外部实用程序(仅用于处理一行)的效率要高:
There's no need for grep
here: bash has built-in regex support, which is vastly more efficient to use than starting up an external utility just to process a single line:
re='^PR-([0-9]+)'
s='PR-1769|7bb12d4152a497cef491e0a1088b3984ad92972f|marvel|'
if [[ $s =~ $re ]]; then
echo "Matched: ${BASH_REMATCH[1]}"
fi
您还可以使用参数扩展:
You can also use parameter expansions:
s='PR-1769|7bb12d4152a497cef491e0a1088b3984ad92972f|marvel|'
s="${s%%'|'*}" # trim off everything after the first |
s="${s#PR-}" # trim off the leading PR
echo "$s"
顺便说一句,如果您需要提取各个字段,那么 read
可能是该工作的正确工具:
If you needed to extract the individual fields, by the way, read
might be the correct tool for the job:
s='PR-1769|7bb12d4152a497cef491e0a1088b3984ad92972f|marvel|'
IFS='|' read -r pr hash username <<<"$s"
...上面将把 PR-1769
放入变量 pr
中,将 7bb12d4152a497cef491e0a1088b3984ad92972f
放入变量 hash
,然后将 marvel
放入变量 username
中.那么,要剥离 PR-
,可能看起来像这样:
...the above will put PR-1769
into the variable pr
, 7bb12d4152a497cef491e0a1088b3984ad92972f
into the variable hash
, and marvel
into the variable username
. To strip off the PR-
, then, might simply look like:
echo "${pr#PR-}"
...或打印提取的用户名:
...or, to print the extracted username:
echo "$username"
请参阅:
See:
- BashFAQ#100 (如何在bash中进行字符串操作?")
- bash-hackers.org参数扩展参考
- BashFAQ #100 ("How do I do string manipulations in bash?")
- bash-hackers.org parameter expansion reference
这篇关于如何使用bash解析字符串以获取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!