Linux Bash shell 脚本来获取子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8770267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash shell script to grab a substring?
提问by Hyman
For example- $x=xyz.2.3.4.fc15.i686
output require=15
(i.e. between fc and .i686)
例如 -$x=xyz.2.3.4.fc15.i686
输出 require=15(即在 fc 和 .i686 之间)
采纳答案by kev
$ x=xyz.2.3.4.fc15.i686
$ y=${x#*fc}
$ z=${y%.*}
$ echo $z
15
#
left strip%
right strip
#
左带%
右带
回答by Zsolt Botykai
There are several ways to do it. If the original string's length is constant, you can use cut
like:
有几种方法可以做到。如果原始字符串的长度是常数,则可以使用cut
如下:
echo YOUR_INPUT_STRING | cut -b n-z
where n
is the starting and z
is the ending position.
哪里n
是起点,哪里是z
终点。
If the number of dots is constant, try:
如果点数不变,请尝试:
echo YOUR_INPUT_STRING | cut -d '.' -f 5 | cut -b 3-
Or you can use something like awk
或者你可以使用类似的东西 awk
echo YOUR_INPUT_STRING | awk '{print gensub(".*fc([0-9]+)\.i686","\1","g",bash-4.2$ x='xyz.2.3.4.fc15.i686'
bash-4.2$ tempx="${x#*fc}"
bash-4.2$ echo "${tempx%.i686}"
15
)}'
HTH
HTH
回答by manatwork
With bash
or ksh
you need no external utility:
使用bash
或ksh
您不需要外部实用程序:
bash-4.2$ x='xyz.2.3.4.fc15.i686'
bash-4.2$ echo "${x:12:2}"
15
Or if you want it by position, similar to another answerbut without external utilities:
或者,如果您按位置想要它,类似于另一个答案,但没有外部实用程序:
bash-4.2$ x='xyz.2.3.4.fc15.i686'
bash-4.2$ [[ "$x" =~ fc(.+)\.i686 ]]
bash-4.2$ echo "${BASH_REMATCH[1]}"
15
Or if you want it with regular expression, similar to another answerbut without external utilities (this time bash
only):
或者,如果您希望使用正则表达式,类似于另一个答案,但没有外部实用程序(bash
仅这次):
echo $x | sed 's/.*fc\([0-9]*\)\.i686//'
回答by Birei
One way using sed
:
一种使用方式sed
:
[jaypal:~/Temp] awk -F. '{print substr (,3,2)}' <<< x=xyz.2.3.4.fc15.i686
15
回答by jaypal singh
You can use awk
您可以使用 awk