bash 如何从bash中第一次出现模式开始获取子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6863252/
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-09-18 00:28:53  来源:igfitidea点击:

how to get substring, starting from the first occurence of a pattern in bash

bashshell

提问by iliaden

I'm trying to get a substring from the start of a pattern.

我试图从模式的开头获取子字符串。

I would simply use cut, but it wouldn't work if the pattern is a few characters long.

我会简单地使用cut,但如果模式是几个字符长,它就行不通。

if I needed a single-character, delimiter, then this would do the trick:

如果我需要一个单字符的分隔符,那么这可以解决问题:

result=`echo "test String with ( element in parenthesis ) end" | cut -d "(" -f 2-`

edit: sample tests:

编辑:示例测试:

 INPUT: ("This test String is an input", "in")
 OUTPUT: "ing is an input"

 INPUT: ("This test string is an input", "in ")
 OUTPUT: ""

 INPUT: ("This test string is an input", "n")
 OUTPUT: "ng is an input"

note: the parenthesis mean that the input both takes a string, and a delimiter string.

注意:括号意味着输入都需要一个字符串和一个分隔符字符串。

采纳答案by Costa

EDITED:

编辑:

In conclusion, what was requested was a way to parse out the text from a string beginning at a particular substring and ending at the end of the line. As mentioned, there are numerous ways to do this. Here's one...

总之,所要求的是一种从特定子字符串开始到行尾结束的字符串中解析出文本的方法。如前所述,有很多方法可以做到这一点。这是一个...

egrep -o "DELIM.*" input

egrep -o "DELIM.*" input

... where 'DELIM' is the desired substring.

...其中 'DELIM' 是所需的子字符串。

回答by glenn Hymanman

Also

awk -v delim="in" '{print substr(
result=${string#"${string%%DELIM*}"}
, index(##代码##, delim))}'

回答by jilles

This can be done without external programs. Assuming the string to be processed is in $stringand the delimiter is DELIM:

这可以在没有外部程序的情况下完成。假设要处理的字符串是 in$string并且分隔符是DELIM

##代码##

The inner part substitutes $stringwith everything starting from the first occurrence of DELIM(if any) removed. The outer part then removes that value from the start of $string, leaving everything starting from the first occurrence of DELIMor the empty string if DELIMdoes not occur. (The variable stringremains unchanged.)

内部部分替换$string为从第一次出现DELIM(如果有)开始的所有内容。然后外部部分从 的开头删除该值$string,保留从第一次出现的 开始的所有内容,DELIM或者如果DELIM没有出现空字符串。(变量string保持不变。)