I have a string literal stored in a variable.
fullString="Line 1 Line 2 captcha_decode userEnteredCaptcha poting Line 3"
I only want to extract the word poting
from this string. If I echo the string and pipe the result through a grep as follows:
echo $fullString | grep "captcha_decode userEnteredCaptcha"
I am returned the entire line again in the stdout.
Line 1 Line 2 captcha_decode userEnteredCaptcha poting Line 3
If I use -o option as following
echo $fullString | grep -o "captcha_decode userEnteredCaptcha"
I am returned only the part I had supplied as argument to the -o option
captcha_decode userEnteredCaptcha
I want to extract only the word poting
which comes after captcha_decode userEnteredCaptcha
and is succeeded by other characters Line 3
. How do I use grep to achieve a positive lookbehind and lookahead and extract only poting
?
CodePudding user response:
You may use this sed
solution:
fullString="Line 1 Line 2 captcha_decode userEnteredCaptcha poting Line 3"
sed -E 's/.* captcha_decode userEnteredCaptcha ([^ ] ).*/\1/' <<< "$fullString"
poting
Or this gnu-grep
solution would also work:
grep -oP 'captcha_decode userEnteredCaptcha \K\S ' <<< "$fullString"
poting
CodePudding user response:
1st solution: With your shown samples, please try following awk
code. Written and tested in GNU awk
.
echo "$fullString" |
awk -v RS='captcha_decode userEnteredCaptcha [^ ]*' '
RT{
num=split(RT,arr,FS)
print arr[num]
}'
2nd solution: Using awk
's match
function in GNU awk
's array option for matches found in regex for capturing group.
echo "$fullString" |
awk 'match($0,/captcha_decode userEnteredCaptcha ([^ ]*)/,arr){print arr[1]}'
CodePudding user response:
mawk NF OFS= FS='^.*captcha_decode userEnteredCaptcha | .*$' gawk '$_ = $2' FS='^.*captcha_decode userEnteredCaptcha | .*$'
poting