bash 在bash中给定文本中的两个给定不同分隔符之间提取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23875129/
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 text between two given different delimiters in a given text in bash
提问by dineshdileep
I have a line of text which looks like hh^ay-pau+h@ow
, I want to extract the text between -
and +
which in this case is pau
. This should be done in bash. Any help would be appreciated.
EDIT: I want to extract the text between the first occurence of the tokens
PS: My google search didn't take me anywhere. I apologize if this question is already asked.
我有一行文字看起来像hh^ay-pau+h@ow
,我想提取文本之间-
,并+
在这种情况下pau
。这应该在 bash 中完成。任何帮助,将不胜感激。编辑:我想提取第一次出现的标记之间的文本 PS:我的谷歌搜索没有带我去任何地方。如果已经问过这个问题,我深表歉意。
回答by Bernhard
The way to do this in pure bash
, is by using parameter expansions in bash
在 pure 中执行此操作的方法bash
是在 bash 中使用参数扩展
$ a=hh^ay-pau+h@ow
$ b=${a%%+*}
$ c=${b#*-}
$ echo $c
pau
b: remove everything including and behind the first +
occurence
c: remove everything excluding and before the first -
ocurrence
b:删除第一次出现之后的+
所有内容 c:删除第一次-
出现之前和之前的所有内容
More info about substring removing in bash parameter expansion
有关在 bash 参数扩展中删除子字符串的更多信息
回答by Nicolae Namolovan
If you have only one occurence of -
and +
you can use cut:
如果您只出现一次-
并且+
可以使用 cut:
$ echo "hh^ay-pau+h@ow" | cut -d "-" -f 2 | cut -d "+" -f 1
pau
回答by iruvar
Assuming one occurence of +
and -
, you can stick to bash
假设+
和 出现一次-
,您可以坚持bash
IFS=+- read -r _ x _ <<<'hh^ay-pau+h@ow'
echo $x
pau
回答by Vytenis Bivainis
Try
尝试
grep -Po "(?<=\-).*?(?=\+)"
For example,
例如,
echo "hh^ay-pau+h@ow" | grep -Po "(?<=\-).*?(?=\+)"
回答by eduffy
If you're guarenteed to only have one -
and one +
.
如果你保证只有一-
和一+
。
% echo "hh^ay-pau+h@ow" | sed -e 's/.*-//' -e 's/+.*//'
pau
回答by Emilio Galarraga
echo "hh^ay-pau+h@ow" | awk -F'-' '{print }' |awk -F'+' '{print }'