开发者

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

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.

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 inpu开发者_StackOverflowt", "n")
 OUTPUT: "ng is an input"

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


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

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


Also

awk -v delim="in" '{print substr($0, index($0, delim))}'


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

result=${string#"${string%%DELIM*}"}

The inner part substitutes $string with 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 DELIM or the empty string if DELIM does not occur. (The variable string remains unchanged.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜