Reputation: 107
I want to list files of a directory with ls
that match a pattern without using grep
. Is it possible?
The point is to retrieve all files that match this pattern '^\Extra_text_[0-9]\{10\}.csv'
and count how much I got.
I tried this code:
ls | grep '^\Extra_text_[0-9]\{10\}.csv'
InputName=' | grep ^\Extra_text_[0-9]\{10\}.csv'
fileCount=`ls $INPUT_FILE/$InputName 2>/dev/null | wc -l`
echo "$fileCount
But it doesn't work! :/
Upvotes: 6
Views: 14779
Reputation: 404
You may use file-matching metacharacters.
* matches any number of characters
? matches any one character
[...] matches any one of the characters between the brackets
which can include a hyphen-separated range of letters or numbers
Above just an example, maybe not exactly what you are trying to do. As I can't figure out what your regex means.
ls -l Extra_text_[0-9]{10}.csv | wc -l
You may use the command above to count how many files you get.
Reference
Negus, C. (2020) Linux Bible, 10th Edition. Wiley
Upvotes: 2
Reputation: 4681
Not with ls
only. ls
does not know about patterns at all. It can only be used with globbing (wildcards *
and ?
or extended globbing - see extglob
in the Bash manual page) offered by the shell, but not with regular expressions.
An easy way is to use find
for this job (note that the regex needs to match the whole filename):
find . -regex '<yourpattern>'
To count results, pipe to wc
:
# safe for corner case: version of find w/o newline escaping and files with newlines:
find . -regex '<yourpattern>' -printf '.' | wc -c
# fallback for non-GNU platform, corner cases not addressed:
find . -regex '<yourpattern>' | wc -l
Find -regex
in the find
manual page for more information.
Upvotes: 4