Basic Unix Help

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aemado
    New Member
    • Sep 2007
    • 17

    Basic Unix Help

    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...somethin g like:

    grep LearnCS *.txt | wc -l

    Maybe? Any suggestions would be greatly appreciated!
  • numberwhun
    Recognized Expert Moderator Specialist
    • May 2007
    • 3467

    #2
    Originally posted by aemado
    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...somethin g 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:

    Code:
    ls /home/LearnCS | grep ".txt" | wc -l
    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

    Comment

    • docdiesel
      Recognized Expert Contributor
      • Aug 2007
      • 297

      #3
      Hi,

      Code:
      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):
      Code:
      ls -R $HOME | grep -i ".txt" | wc -l
      Regards,

      Bernd

      Comment

      Working...