bash 从字符串中提取模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11533063/
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
Extract pattern from a string
提问by user1533326
In bash script, what is the easy way to extract a text pattern from a string?
在 bash 脚本中,从字符串中提取文本模式的简单方法是什么?
For example, I want to extract X
followed by 2 digits in the end of the string?
例如,我想X
在字符串末尾提取后跟 2 位数字?
回答by John Kugelman
There's a nifty =~
regex operator when you use double square brackets. Captured groups are made available in the $BASH_REMATCH
array.
=~
使用双方括号时有一个漂亮的正则表达式运算符。捕获的组在$BASH_REMATCH
阵列中可用。
if [[ $STRING =~ (X[0-9]{2})$ ]]; then
echo "matched part is ${BASH_REMATCH[1]}"
fi
回答by Debaditya
Lets take your input as
让我们将您的输入作为
Input.txt
输入.txt
ASD123
GHG11D3456
FFSD11dfGH
FF87SD54HJ
And the pattern I want to find is "SD[digit][digit]"
我想找到的模式是“SD[digit][digit]”
Code
代码
grep -o 'SD[0-9][0-9]' Input.txt
grep -o 'SD[0-9][0-9]' Input.txt
Output
输出
SD12
SD11
SD54
And if you want to use this in script...then you can assign the above code in a variable/array... that's according to your need.
如果你想在脚本中使用它......那么你可以在变量/数组中分配上面的代码......这根据你的需要。
回答by ghoti
$ foo="abcX23"
$ echo "$(echo "$foo" | sed 's/.*\(X[0-9][0-9]\)$//')"
X23
or
或者
if [[ "$foo" =~ X[0-9][0-9]$ ]]; then
echo "${foo:$((${#foo}-3))}"
fi
回答by sfstewman
You can also use parameter expansion:
您还可以使用参数扩展:
V="abcX23"
PREFIX=${V%%X[0-9][0-9]} # abc
SUFFIX=${V:${#PREFIX}} # X23
回答by YadirHB
I need to extract the host port from this string: NIC 1 Rule(0): name = guestssh, protocol = tcp, host ip = , host port = 2222, guest ip = , guest port = 22
我需要从这个字符串中提取主机端口:NIC 1 Rule(0): name = guestsh, protocol = tcp, host ip = , host port = 2222, guest ip = , guest port = 22
That string is obtained by using: vboxmanage showvminfo Mojave | grep 'host port', I mean is filtered and I need to extract whatever number be in the host port; in this case is 2222 but it can be different.
该字符串是通过使用获得的: vboxmanage showvminfo Mojave | grep '主机端口',我的意思是被过滤了,我需要提取主机端口中的任何数字;在这种情况下是 2222 但它可以不同。