Suliman Sharif
Suliman Sharif

Reputation: 607

How to compare a file to a list in linux with one line code?

Hey so got another predicament that I am stuck in. I wanted to see approximately how many Indian people are using the stampede computer. So I set up an indian txt file in vim that has about 50 of the most common surnames in india and I want to compare those names in the file to the user name list.

So far this is the code I have

getent passwd | cut -f 5 -d: | cut -f -d' '

getent passwd gets the userid list which is going to look like this tg827313:x:827313:8144474:Brandon Williams

the cut functions will get just the last name so the output of the example will be

Williams

Now can use the grep function to compare files but how do I use it to compare the getent passwd list with the file?

Upvotes: 0

Views: 50

Answers (1)

John1024
John1024

Reputation: 113864

To count how many of the last names of computer users appear in the file namefile, use:

getent passwd | cut -f 5 -d: | cut -f -d' ' | grep -wFf namefile | wc -l

How it works

  • getent passwd | cut -f 5 -d: | cut -f -d' '

    This is your code which I will assume works as intended for you.

  • grep -wFf namefile

    This selects names that match a line in namefile. The -F option tells grep not to use regular expressions for the names. The names are assumed to be fixed strings. The option -f tells grep to read the strings from file. -w tells grep to match whole words only.

  • wc -l

    This returns a count of the lines in the output.

Upvotes: 1

Related Questions