By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,571 Members | 972 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,571 IT Pros & Developers. It's quick & easy.

Basic Unix Help

P: 17
I am just beginning to learn how to use Unix and its commands. Assuming my home directory is named LearnCS, I want to write out the command to count how many files I have in my home directory that end with the extension *.txt with the resultant answer being a single number.

I believe I need to use grep and piping, but I'm not exactly sure...something like:

grep LearnCS *.txt | wc -l

Maybe? Any suggestions would be greatly appreciated!
Feb 3 '08 #1
Share this Question
Share on Google+
2 Replies

numberwhun
Expert Mod 2.5K+
P: 3,503
I am just beginning to learn how to use Unix and its commands. Assuming my home directory is named LearnCS, I want to write out the command to count how many files I have in my home directory that end with the extension *.txt with the resultant answer being a single number.

I believe I need to use grep and piping, but I'm not exactly sure...something like:

grep LearnCS *.txt | wc -l

Maybe? Any suggestions would be greatly appreciated!
Actually, what you have their will look into each file that matches "*.txt" and search for "LearnCS".

Instead, what you want to do is take a listing, then pipe it through grep for your pattern, then pipe that through wc, like so:

Expand|Select|Wrap|Line Numbers
  1. ls /home/LearnCS | grep ".txt" | wc -l
  2.  
You don't need the * ".txt" because it isn't doing any type of globbing, instead, it is just a pattern to be looked for. I am only doing an "ls" and not an "ls -l" because I don't want the full listing, just the file names in the directory.

Just as a help to you, here are some links to some good sites for Unix commands and learning Unix. There are many, but these are some that I found:

Unix Command Reference Card
Intro to Unix Commands
Unix Tutorial For Beginners

Happy learning!

Regards,

Jeff
Feb 3 '08 #2

docdiesel
Expert 100+
P: 297
Hi,

Expand|Select|Wrap|Line Numbers
  1. ls $HOME/*.txt | wc -l
should be enough. Except if you've got txt files in subdirectories (use ls -R with -R for recursive listing) and aren't sure if they end on .txt or .TXT (use grep -i with -i for case insensitivity):
Expand|Select|Wrap|Line Numbers
  1. ls -R $HOME | grep -i ".txt" | wc -l
Regards,

Bernd
Feb 3 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.