2

I have some troubles with combining ls and grep. The thing is that I have to use only ls and grep to list all files in home directory. Ive tried multiple of combinatnions but with no effect. I think i should use it like:

ls /home/mydir | grep stomething

The next question is (no idea how to do this) how to use ls and another command to count number of dirs in main folder?

  • look at the output of ls -lA and grep the results ;) – Panther Jan 27 '15 at 5:19
5

Your usage of ls and grep is correct, that will find any results in the ls output containing 'stomething'. Note that looks at the whole line, not just the filename (mostly applicable when using certain flags with ls, such as ls -l etc).

Finding directories, you're better off using find and wc (wordcount):

find /home/mydir -maxdepth 1 -mindepth 1 -type d | wc -l

Explanation:

  • maxdepth 1, count to a maximum depth in the tree of 1 (eg only dirs, not subdirs in this case)
  • mindepth 1, basically used in that example to make sure find doesn't find "." also.
  • type d, look for directories (-type f will find files, l will find soft links etc)
  • wc -l, count the lines returned

If you run that without the pipe to wc you'll get a list of all the results. Find is a pretty handy command to be familiar with.

| improve this answer | |

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.