Grep one file against another

This came in handy the other day, I was looking to grep a list of things I needed against a list of things I had available. I’d quite forgotten I knew how to do this until it suddenly sprang on me that I needed to and didn’t want to write a script to do it. Of course you could do a either or expression but that loses the fun aspect when you have many different things you’re looking for.

I’ve included both methods here, I prefer -a but not all copies of xargs support it (MacOSX seems to lack it).

xargs -a want.list -I {} grep {} available.list

cat ./want.list | xargs -I {} grep {} available.list

If you have pattens which match multiple entries you could use sort to clean that up.

xargs -a want.list -I {} grep {} available.list | sort -u

cat ./want.list | xargs -I {} grep {} available.list | sort -u

You can take this further if you’re trying to clean up a file system you could do the following.

xargs -a want.list -I {} grep {} available.list | sort -u | xargs rm

cat ./want.list | xargs -I {} grep {} available.list | sort -u | xargs rm

This has all sorts of applications throughout text manipulation. I’ve found it especially useful to pull through log files where you’re looking for 20-30 different expressions.

Regards,
Robert Small.

Advertisement
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s