[英]How to grep only two words in a line in file between them specific number of random words present
Given a file with this content: 给定一个具有以下内容的文件:
Feb 1 ohio a1 rambo
Feb 1 ny a1 sandy
Feb 1 dc a2 rambo
Feb 2 alpht a1 jazzy
I only want the count of those lines containing Feb 1
and rambo
. 我只想要包含Feb 1
和rambo
的那些行的计数。
You can use awk
to do this more efficiently: 您可以使用awk
来更有效地执行此操作:
$ awk '/Feb 1/ && /rambo/' file
Feb 1 ohio a1 rambo
Feb 1 dc a2 rambo
To count matches: 要计算匹配数:
$ awk '/Feb 1/ && /rambo/ {sum++} END{print sum}' file
2
awk '/Feb 1/ && /rambo/'
is saying: match all lines in which both Feb 1
and rambo
are matched. awk '/Feb 1/ && /rambo/'
表示:匹配Feb 1
和rambo
都匹配的所有行。 When this evaluates to True, awk performs its default behaviour: print the line. 当此评估为True时,awk将执行其默认行为:打印行。
awk '/Feb 1/ && /rambo/ {sum++} END{print sum}'
does the same, only that instead of printing the line, increments the var sum
. awk '/Feb 1/ && /rambo/ {sum++} END{print sum}'
作用相同,仅是代替打印行,而是增加var sum
。 When the file has been fully scanned, it enters in the END
block, where it prints the value of the var sum
. 完全扫描文件后,它将进入END
块,在该块中打印var sum
的值。
Try this as per @Marc's suggestions, 按照@Marc的建议尝试一下,
grep 'Feb 1.*rambo' file |wc -l
In case, position of both strings are not sure to be as mentioned in question following command will be useful, 如果不确定两个字符串的位置是否如问题中所述,以下命令将很有用,
grep 'rambo' file|grep 'Feb 1'|wc -l
The output will be, 输出将是
2
Here is what I tried, 这是我尝试过的
Is Feb 1 always before rambo? 2月1日是否总是在兰博之前? if yes: 如是:
grep -c "Feb 1 .* rambo"
awk解决方案可能更清晰,但这是一种不错的sed技术:
sed -n '/Feb 1/{/rambo/p; }' | wc -l
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.