Let's say we have a string and its delimiter is ?:Leslie Cheung April 1 ? Elvis August 16 ? Leonard Nimoy February 27I know how to grep the first substring between delimiters:echo $above_string | grep -oP ^[^?]*Leslie Cheung April 1How should I change the Regex in order to grep the second or third substring?
How to grep the n-th substring between given delimiters?
command line;grep;regular expression
echo $above_string | grep -oP ^([^?]*\?){2}\K[^?]*Change 2 to the n - 1 value in order to obtain the nth string.This assumes that you want the nth string in that line. You have n - 1 strings with no ? ending with a literal '?' (\? since it's a special character in perl regex). Then with \K you state you are not interested in the previous contents, thus extracting just the following text until the next separator.