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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:58:03  来源:igfitidea点击:

Bash shell script to grab a substring?

linuxbashshell

提问by Hyman

For example- $x=xyz.2.3.4.fc15.i686output 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 cutlike:

有几种方法可以做到。如果原始字符串的长度是常数,则可以使用cut如下:

echo YOUR_INPUT_STRING | cut -b n-z 

where nis the starting and zis 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 bashor kshyou need no external utility:

使用bashksh您不需要外部实用程序:

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 bashonly):

或者,如果您希望使用正则表达式,类似于另一个答案,但没有外部实用程序(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

##代码##