0
  1. List item

I/P:

abcd_Server1 CCDDomain
defg_Server1 GGFDomain
kdkhs_Server1 CCDDomain
abce_Server1 CCDDomain
dgdg_Server1 CCADomain
dfdkhs_Server1 GGFDomain

I need to search for the word "Domain" and then count the unique occurrences of the word.

In above case the output should be 3 since 3 different names are there (CCDDomain,GGFDomain,CCADomain)

I have tried using this :

grep -oh '*Domain' "ServerNames.txt" | sort -u | wc -l 

('-oh' I got from another answer)

3

For the number of occurrences of each of the different words that contain Domain, with GNU grep or compatible.

  • for words delimited by spacing characters:

    <file grep -o '\S*Domain\S*' | sort | uniq -c
    
  • for words defined as sequences of alnums or underscores (anything else being delimiters:

    <file grep -o '\w*Domain\w*' | sort | uniq -c
    
1

You can simply wrap you match pattern with the \w pattern, like this :

% grep -oh "\w*Domain\w*" ServerNames.txt
CCDDomain
GGFDomain
CCDDomain
CCDDomain
CCADomain
GGFDomain

Then you can go ahead with sort -u and wc -l

% grep -oh '\w*Domain\w*' ServerNames.txt | sort -u | wc -l 
3
  • 1
    You mean \w*, of course? – AlexP Jun 14 '18 at 11:48
  • or [[:alpha:]] instead of \w if you don't want numbers and underscores to match – ilkkachu Jun 14 '18 at 12:15
0
grep -o '[[:alpha:]]*Domain[[:alpha:]]*' ServerNames.txt | sort | uniq | wc -l

or

grep -o '\w*Domain\w*' ServerNames.txt | sort | uniq | wc -l

[[:alpha:]]* means 0 or more letters. So the grep will find sequences of letters including 'Domain', and output them to be sorted and uniqued. (-h not needed when only one file is to be grepped.)

0

Old-good awk approach:

$ awk '$2 ~ /Domain/ && !a[$2]++{ cnt++ }END{ print cnt }' ServerNames.txt
3

With GNU coreutils you may apply (in case if Domain is always occurs as a 2nd column of each line):

$ uniq -f1 <(sort -k2 ServerNames.txt) | wc -l
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.