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
.
You can use awk
to do this more efficiently:
$ 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. When this evaluates to True, awk performs its default behaviour: print the line.
awk '/Feb 1/ && /rambo/ {sum++} END{print sum}'
does the same, only that instead of printing the line, increments the var sum
. When the file has been fully scanned, it enters in the END
block, where it prints the value of the var sum
.
Try this as per @Marc's suggestions,
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? if yes:
grep -c "Feb 1 .* rambo"
awk解决方案可能更清晰,但这是一种不错的sed技术:
sed -n '/Feb 1/{/rambo/p; }' | wc -l
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.