user1161064
user1161064

Reputation: 65

listing files in the directory using grep

List all the files in /usr/bin whose filenames contain lowercase English alphabet characters only and also contain the word file as a (contiguous) substring.

For example, file and profiles are such files, but git-ls-files is not.

This is the exact question I have and I can only use grep, ls, cat and wc for it.

ls /usr/bin/ | grep '[^-]*file'

This is what I got so far and output is below. I dont know how to display for example just file since * is zero or more occurences. And no idea how to put lowercase thing in the regex as well..

check-binary-files
clean-binary-files
desktop-file-install
desktop-file-validate
ecryptfs-rewrite-file
file
filep
git-cat-file
git-diff-files
git-ls-files
git-merge-file
git-merge-one-file
git-unpack-file
lockfile
nsrfile
pamfile
pcprofiledump
pnmfile
ppufiles
profiles

Upvotes: 2

Views: 754

Answers (4)

Using ls piped with grep is really redundant in that situation. You can use find:

$> find /usr/bin -regex "/usr/bin/[a-z]*file[a-z]*" -type f -printf "%f\n"
profiles
keditfiletype
inifile
dotlockfile
pamfile
pnmfile
file
konsoleprofile

Upvotes: 1

insider
insider

Reputation: 1958

Use -P option, means Perl regular expressions, so finally your command would look like:

ls /usr/bin | grep -P '[a-z]file'

insider@gfl ~/test/bin$ ls
123file             desktop-file-install   file          git-diff-files  git-merge-one-file  nsrfile        pnmfile   testlist
check-binary-files  desktop-file-validate  filep         git-ls-files    git-unpack-file     pamfile        ppufiles
clean-binary-files  ecryptfs-rewrite-file  git-cat-file  git-merge-file  lockfile            pcprofiledump  profiles
insider@gfl ~/test/bin$ ls . | grep -P '[a-z]file'
lockfile
nsrfile
pamfile
pcprofiledump
pnmfile
ppufiles
profiles

Upvotes: 0

ori
ori

Reputation: 7847

ls -1 /usr/bin | grep '^[a-z]*file[a-z]*$'

ls -1 makes sure the files are listed each in a single line. ^ and $ are symbols for start and end of line, which is what you were missing (otherwise it can match a substring of the filename)

Upvotes: 0

nmichaels
nmichaels

Reputation: 50941

ls /usr/bin/ | grep --regex '^[[:lower:]]*file[[:lower:]]*$'

The ^ and $ match the beginning and end of the string, respectively.

Upvotes: 1

Related Questions