shellgrepregex-lookaroundscshpositive-lookahead

Why is my grep lookahead retrieving the same value twice?


Context: I am trying to use cat|grep lookahead to get the very next word in a file after grep finds the original targetword(including the colon), so I can set a variable to equal that word.

For example: TARGETWORD: NEXTWORD

set myVariable = `cat File.txt | grep -oP '(?<=TARGETWORD: )[^ ]*'`

I then echo the term so I can confirm that grep retrieved the word.

echo $myVariable

The expression above works but for some reason whenever it finds the TARGETWORD rather than setting myVariable equal to the target word once it repeats it doubly so with a space inbetween.

Expected output:

echo $myVariable

output: NEXTWORD

Actual output:

echo $myVariable

output: NEXTWORD NEXTWORD

Solution

  • I ended up finding the issue. Felt quite silly after figuring out what it was, but it was simply that there were two instances of my grep "TARGETWORD" instead of one in the file.txt so it was returning both values to the variable.