Listing files with grep?
I have a directory that contains the following files:
file1a file1ab file12A2 file1Ab file1ab
I want to list all files that start with file1
and followed by two letter at most!
The solution I have proposed is as follows:
ls | grep -i file1 [az] {2}
But it does not work!
I want to know why? and how to list?
You don't need piping, grep
or ls
. Just use shell globbing.
In bash
, using extglob
pattern (should be enabled by default in interactive sessions, if not do shopt -s extglob
to set it first):
file1@(|?|??)
?
matched any single character, @(||)
selects any of the patterns separated by |
.
If you only meant to match any characters between a-z
and A-Z
, use use character class [:alpha:]
which denotes all alphabetic characters in the current locale:
file1@(|[[:alpha:]]|[[:alpha:]][[:alpha:]])
Example:
$ ls -1
file1
file112
file11a
file12A2
file1a
file1ab
file1Ab
file1as
file2
fileadb
$ ls -1 file1@(|[[:alpha:]]|[[:alpha:]][[:alpha:]]))
file1
file1a
file1ab
file1Ab
file1as
zsh
supports this natively:
file1(|[[:alpha:]]|[[:alpha:]][[:alpha:]])
I am answering this portion very reluctantly, upon request from OP.
Any future reader, Don't parse ls
, use globbing.
Using ls
and grep
:
ls | grep -E '^file1[[:alpha:]]{,2}$'
Example:
% ls | grep -E '^file1[[:alpha:]]{,2}$'
file1
file1a
file1ab
file1Ab
file1as
Whats about find?
find . -maxdepth 1 -regextype posix-egrep -iregex '\./file1[a-z]{,2}.*'