简体   繁体   English

为什么我的 grep 前瞻两次检索相同的值?

[英]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.上下文:在 grep 找到原始目标词(包括冒号)后,我正在尝试使用 cat|grep 前瞻来获取文件中的下一个单词,因此我可以设置一个变量来等于该单词。

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.然后我回显该术语,以便确认 grep 检索到了该词。

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.上面的表达式有效,但由于某种原因,每当它找到 TARGETWORD 而不是将 myVariable 设置为等于目标词时,它会重复两次,因此中间有空格。

Expected output:预期输出:

echo $myVariable

output: NEXTWORD

Actual output:实际输出:

echo $myVariable

output: NEXTWORD NEXTWORD

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.在弄清楚它是什么之后感觉很傻,但这只是我的 grep "TARGETWORD" 的两个实例而不是 file.txt 中的一个实例,因此它将两个值都返回给变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM