简体   繁体   English

使用grep查找一行中的特定模式

[英]Use grep to find a specific pattern in a line

I am trying to find a specific pattern in a text file using grep inside a bourne shell script 我正在尝试在bourne shell脚本中使用grep在文本文件中找到特定模式

The style is: word1 word2 word3 样式是: word1 word2 word3

I want to print everything that is not of that style. 我想打印所有不是这种风格的东西。 So far I used 到目前为止,我使用

grep -e '[[:space:]]\{2,\}' somefile

to find more than 2 empty spaces between the words, but I cannot figure out how to make it so that the 3 word per line limit is retained. 在两个单词之间找到两个以上的空格,但我无法弄清楚如何做到这一点,以便保留每行3个单词的限制。

My other method would be to also count how many words there are per line and if it exceeds 3, to print the line. 我的另一种方法是还计算每行有多少个单词,如果超过3个,则打印该行。 Or to check for a white space at the end of the 3rd word, but I am unsure how that would be formatted. 还是要检查第三个单词的末尾是否有空格,但是我不确定该如何格式化。

I'm not sure if that's what you wanted, but here: 我不确定这是否是您想要的,但是在这里:

 ]$ cat input one one two one two three one two three four ]$ grep -v -e "^[^[:space:]]\\+ [^[:space:]]\\+ [^[:space:]]\\+$" input one one two one two three four 

We match: 我们匹配:

  • any number of not spaces: [^[:space:]]\\+ 任意数量的非空格: [^[:space:]]\\+
  • until we get a space 直到我们得到一个空间
  • repeated 3 times 重复3次
  • all this should be in one line: ^...$ 所有这些都应该在一行中: ^...$
  • and we negate this with -v option 我们用-v选项取反

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

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