Git Bash - 在文件(或字符串)中查找匹配指定子字符串的单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26721446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:41:44  来源:igfitidea点击:

Git Bash - find words in a file (or string) matching specified sub-string

bashword

提问by Pascal

cmd: cat test.txt | grep pin
results: prints all lines containing pin

cmd: cat test.txt | grep pin
结果:打印所有包含 pin 的行

I want to now only grep for words containing pin. What is the command to so that?

我现在只想 grep 包含 pin 的单词。这样做的命令是什么?

Thanks!

谢谢!

All, thank you for your comments. I am using the Git Bash (version 1.9.4). The grep in this shell do not have the -o option. There is a -w option. I tried: grep -w 'pin' test.txt but it returns nothing.

所有,谢谢您的意见。我正在使用 Git Bash(版本 1.9.4)。此 shell 中的 grep 没有 -o 选项。有一个 -w 选项。我试过: grep -w 'pin' test.txt 但它什么都不返回。

Anyone using Git Bash to solve this issue?

有人使用 Git Bash 来解决这个问题吗?

Thank you all.

谢谢你们。

回答by celeritas

Assuming your file is called test.txt, you can do:

假设您的文件名为test.txt,您可以执行以下操作:

grep -o '\S*pin\S*' test.txt

grep -o '\S*pin\S*' test.txt

The -oflag will print only the matching words on the line, as opposed to the whole line.

-o标志将仅打印该行上的匹配单词,而不是整行。

回答by anubhava

You can use:

您可以使用:

grep -o '[^[:blank:]]*pin[^[:blank:]]*' test.txt

回答by Sriharsha Kalluru

You can use -w option.

您可以使用 -w 选项。

$ cat test
pin
PIN
somepin
aping
spinx
$ grep pin test
pin
somepin
aping
spinx
$ grep -w pin test
pin
$