简体   繁体   中英

Counting number of words that contain a substring with grep

I am trying to grep a file for the words that contain "owner" but not the word owner itself. So, "ownership" for example would be counted.

I know:

grep -o -c owner  #Print only matched words.  ship(owner)ship --> owner

grep -w -c owner #Match only whole words. ownership (No), owner (Yes) 

But it returns the whole standalone word "owner" still.

Whats the correct way to do this?

try this

grep -Pc '(\wowner)|(owner\w)' file

the word should have either a prefix or suffix (so the standalone won't match). Note that this will count the number of lines that have a match. To count the occurances

grep -oP '(\wowner)|(owner\w)' file | 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.

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