I Have a single line as follows, I need all the words between select and Done
vertical on; select blah blah blah contains all special characters including /*?&; Done
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityUsing bash regular expression would give (assuming the line in a variable):
$ line="vertical on; select blah blah blah contains all special characters including /*?&; Done"
$ [[ "$line" =~ select(.*)Done ]] && echo ${BASH_REMATCH[1]}
blah blah blah contains all special characters including /*?&;
Using Perl-compatible regular expressions (PCRE):
(?<=word1).*?(?=word2)
Applying the above pattern with GNU grep
:
$ grep -Po '(?<=select).*?(?=Done)' <<< ' vertical on; select blah blah blah contains all special characters including /*?&; Done'
blah blah blah contains all special characters including /*?&;
Explanation
(?<=word1)
: Match word1
before the current position but don't include it in the result..*?
: Match any string.(?=word2)
: Match word2
after the current position but don't include it in the result.The (?<=word1)
and (?=word2)
patterns are collectively known as lookaround. This feature is not supported by POSIX engines (BRE and ERE) so you need a more powerful engine (such as PCRE).
grep
's standard input. With Bash: grep -Po '(?<=select).*?(?=Done)' <<< "${var}"
(note that there will be a trailing newline). With any other POSIX shell (Bash included): printf '%s' "${var}" | grep -Po '(?<=select).*?(?=Done)'
(there's no trailing newline by default, but you can add it with \n
in the first argument of printf
).
something select blah selection foo Done
? orsomething else is done and Done
?