How to get count of files in a directory starting with specific text like dataxxx.csv
2 Answers
There are probably fancier ways, but what works for me is
ls /directory/data* | wc -l - foo=$(ls /directory/data* | wc -l)Peregrino69– Peregrino692014-12-14 07:49:01 +00:00Commented 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– PM 2Ring2014-12-14 12:48:56 +00:00Commented 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 :)Peregrino69– Peregrino692014-12-14 13:01:26 +00:00Commented Dec 14, 2014 at 13:01
- The naked
$()is ok here, but it's a good habit to double quote stuff: From BashGuideAs 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– PM 2Ring2014-12-15 03:59:29 +00:00Commented Dec 15, 2014 at 3:59
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 - jasonwryan, your code find the files in subdirectory also but how can i find files only in current directory?user188979– user1889792014-12-14 08:26:36 +00:00Commented Dec 14, 2014 at 8:26
- @user188979 you would use
find . -maxdepth 1 ...to restrict the search to just the current directory.Chris Davies– Chris Davies2016-12-14 23:21:35 +00:00Commented Dec 14, 2016 at 23:21
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.