[英]Bash - get String between two characters
how can i get the string between two specific characters, only in bash [with out using grep or sed]我怎样才能得到两个特定字符之间的字符串,仅在 bash [不使用 grep 或 sed]
eg例如
input=hostname~web:sit
I want to extract web
from the above input我想从上面的输入中提取web
${hostname#*~}
gives me output as web:sit
, but i need only web
in the output ${hostname#*~}
给了我 output 为web:sit
,但我只需要web
中的 web
From the other post i can see从另一篇文章我可以看到
% strips from end of $var,
up to pattern. % strips from end of $var,
直到模式。 But not sure how to apply it.但不确定如何应用它。
Any help please请提供任何帮助
Do it in two steps:分两步进行:
input=hostname~web:sit
rightpart=${input#*~} # remove prefix up to "~" (included)
output=${rightpart%:*} # remove suffix from ":" (included)
echo $output
Using extglob
in bash
, you can do this in single step :在bash
extglob
您可以一步完成:
shopt -s extglob
input='hostname~web:sit'
echo "${input//@(*~|:*)/}"
web
Here @(*~|:*)
matches a substring from start to ~
character OR a substring from :
to end.这里@(*~|:*)
匹配从开始到~
字符的 substring 或从:
到结束的 substring。 Using //
we replace all such instances with an empty string.使用//
我们将所有此类实例替换为空字符串。
There is a sed
solution as well:还有一个sed
解决方案:
sed -E 's/.*~([^:]+):.*/\1/' <<< "$input"
web
Another option, using cut
wich is available from the GNU Core Utilities :另一种选择,使用cut
wich 可从GNU Core Utilities获得:
~
把一切都抛在脑后~
:
获取所有之前:
input='hostname~web:sit'
echo "$input" | cut -d '~' -f2 | cut -d ':' -f1
# web
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.