linux bash,只能用grep获取单个单词

发布于 2025-02-13 11:50:58 字数 313 浏览 0 评论 0原文

我有一个很大的文本文件,我必须找到所有的“ knr” - alias。我删除了所有评论和空排:

cat file | grep -v ^# | grep -v ^$ >> Test.txt

我只能得到一个单词,我需要从“ test.txt”文件中写出一个单词? 我真的只需要一个单词,它的结构是: “ KNR00000000000000000_THITS” 我不知道这是否可能,但是在这种结构之后。总有一个空间。

我还需要一些帮助,如何使第一行代码在脚本中起作用。

任何帮助将不胜感激。 善良的是埃利亚斯

I have a large textfile and I have to find all of the "KNR"-alias. I removed all comments and empty lines with this:

cat file | grep -v ^# | grep -v ^$ >> Test.txt

How can I only get this one word, that I need to write out of the "Test.txt" file?
I really only need one word, which has the structure of:
"KNR00000000000000000_THING"
I don´t know if this is possible, but after that structure. there is always a space.

I also need some help with how to make that first line of code work in a script.

Any help would be very appreciated.
Kind regards Elias

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

葬シ愛 2025-02-20 11:50:58

根据注释:

grep -ohE 'KNR[^ ]*' file

将使用grep来匹配您的模式。 [^]表示空间之外的任何内容。

其他可能性是sed

sed -nE "s/.*(KNR.*) .*/\1/p

或 @f.hauri的

tr < file \  \\n | grep ^KNR

这是假设knr是在空间之后或线路开始时。

As per comments:

grep -ohE 'KNR[^ ]*' file

will use grep to match your pattern as I understand it. [^ ] means anything but a space.

Other possibilities are sed:

sed -nE "s/.*(KNR.*) .*/\1/p

or @F.Hauri's

tr < file \  \\n | grep ^KNR

This assumes that the KNR is either after a space or at the start of a line.

旧竹 2025-02-20 11:50:58

如果您只需要这个单词并注意,那么

grep -vE '^#|^

如果有几个单词与此模式匹配,您当然可以做一个。

说明:

-o:仅输出匹配模式的零件
-w:只匹配单词
-e:打开扩展的正则是(以便可以使用+)。

我还修改了您的测试以删除。我的模式以##以及包含零字符的所有行删除所有行。

file | grep -owE KNR0+_THING

如果有几个单词与此模式匹配,您当然可以做一个。

说明:

-o:仅输出匹配模式的零件
-w:只匹配单词
-e:打开扩展的正则是(以便可以使用+)。

我还修改了您的测试以删除。我的模式以##以及包含零字符的所有行删除所有行。

If you only need this word and noting else, you could do a

grep -vE '^#|^

Of course if there are several words matching this pattern, you get all of them.

Explanation:

-o : Output only the part matching the pattern
-w : Match only words
-E : Turn on extended regex (so that + can be used).

I also modified your test for lines to remove.My pattern removes all lines starting with a #, and those which contain zero characters.

file | grep -owE KNR0+_THING

Of course if there are several words matching this pattern, you get all of them.

Explanation:

-o : Output only the part matching the pattern
-w : Match only words
-E : Turn on extended regex (so that + can be used).

I also modified your test for lines to remove.My pattern removes all lines starting with a #, and those which contain zero characters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文