5

I have many files in a folder for example

Kiran.txt
Kiran1.txt
Kiran221.txt
Kiran144.txt
Time.csv
Timer.csv
Timer2.csv
Timer444.csv
Timer266.csv
Account.sh
Account3.sh
Account3333.sh
Account3333.sh
Account333333.sh

From this directory, I want to know how I could use grep to display files based on part of their filename - for example those starting with "Account" or those ending in ".sh".

2
  • Thanks @DMA, I was just gonna do the same, you were a second faster. user663724, if you have similar questions, why not group them in one?
    – slhck
    Sep 14, 2011 at 10:18
  • Nice edit, I thought I was looking at a different question at first, until I realised that the title and content had been modified to make the question more useful to a wider audience.
    – Joe Taylor
    Sep 14, 2011 at 10:25

4 Answers 4

10

You can find

find -type f -name "Account*"

Alternative 2 (this might include folder as well)

ls -1 Account*

Alternative 3 (grep, this could include folder as well)

ls -1 | grep -E "^Account"
1
  • 1
    I prefer find :-)
    – ajreal
    Sep 14, 2011 at 10:15
10

Use a wildcard (What is this wildcard?):

ls *.sh

The * will match anything before the ending .sh that you want. Use the other ls options for displaying, e.g. -l to make it a long listing. See man ls for more info about what you can do with it.

Note that ls would also list any directory ending with .sh, not only files.


You can also use find to overcome this problem.

find . -type f -maxdepth 1 -name "*.sh"

This command only lists "real" files. Using find is something I'd recommend if you want to do something with the found files afterwards. You can do this with the -exec option.

3
  • For OP: In addition, you can also use ? for a single charector as in "hel?o" to find "hello " and "helwo"
    – Sirex
    Sep 14, 2011 at 9:43
  • 1
    I would put quotes around *.sh in the find command, as otherwise the shell would expand it to find . -type f -maxdepth 1 -name Account.sh Account3.sh Account3333.sh Account333333.sh in the question sample.
    – BennyInc
    Sep 14, 2011 at 9:58
  • @BennyB Right, forgot them while copying. Thanks!
    – slhck
    Sep 14, 2011 at 10:01
3

The standard solution is a pipe:

ls | grep ^Account

With something as simple as "Files starting with Account", globs would also work:

ls Account*

but in general a grep is more powerful, and it doesn't run the risk of overflowing the maximum command line length if your folder is really, really full.

3

Use the following command

   ls *.sh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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