3

How to get count of files in a directory starting with specific text like dataxxx.csv

1
  • 1
    What is "a directory start"? Do you want to search in a directory named "start". Do you want to search for file with names starting with "dataxxx.csv" (e.g. dataxxx.csv.123.jpeg)? Or does the text have to in the file? At the start of the files you want to count? Please rewrite you question so it is less ambiguous.
    – Anthon
    Dec 14, 2014 at 8:12

2 Answers 2

5

There are probably fancier ways, but what works for me is

ls /directory/data* | wc -l
4
  • foo=$(ls /directory/data* | wc -l) Dec 14, 2014 at 7:49
  • Shouldn't that be data*.csv? And in your comment, there ought to be double-quotes around the $(). Of course, this strategy will not give a correct count if there are files that match the pattern which happen to have a newline char in their name. :)
    – PM 2Ring
    Dec 14, 2014 at 12:48
  • Yes, of course it can be data*.csv as well :) I haven't quoted $() when I do this kind of thing and haven't noticed anything breaking. I assume something could - what? And you're of course right about about the names. In any case there are now better answers for the OP than mine :) Dec 14, 2014 at 13:01
  • The naked $() is ok here, but it's a good habit to double quote stuff: From BashGuide As with all substitutions, the results of a command substitution will undergo WordSplitting, unless the whole thing is inside double quotes. So as a rule, quote stuff unless you explicitly want to invoke word splitting.
    – PM 2Ring
    Dec 15, 2014 at 3:59
2

Using find to test that they are a file (-type f) and match the required pattern ("data*.csv"):

find directory/ -type f -name "data*.csv" | wc -l
2
  • jasonwryan, your code find the files in subdirectory also but how can i find files only in current directory?
    – user188979
    Dec 14, 2014 at 8:26
  • @user188979 you would use find . -maxdepth 1 ... to restrict the search to just the current directory.
    – roaima
    Dec 14, 2016 at 23:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.