# Check if file exists for part of the filename

**URL:** <https://rubytalk.org/t/check-if-file-exists-for-part-of-the-filename/45174>\
**Category:** ruby-talk\
**Created:** [14 March 2008 08:33 UTC](https://rubytalk.org/t/check-if-file-exists-for-part-of-the-filename/45174 "2008-03-14T08:33:29Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Christian\_Kerth](https://avatars.discourse-cdn.com/v4/letter/c/a88e57/32.png) [@Christian\_Kerth](https://rubytalk.org/u/Christian_Kerth)\
**Post date:** [14 March 2008 08:33 UTC](https://rubytalk.org/t/check-if-file-exists-for-part-of-the-filename/45174/1 "2008-03-14T08:33:29Z")

</div>

Hey!

How do i check if a file exists, that starts with a certain identifier?

e.g. Files in Directory

file\_1.rb  
file\_2.rb  
test\_1.rb

I only want to know if a file exists, that starts with "file\_"

thx

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Mark\_Bush](https://avatars.discourse-cdn.com/v4/letter/m/e274bd/32.png) [@Mark\_Bush](https://rubytalk.org/u/Mark_Bush)\
**Post date:** [14 March 2008 09:02 UTC](https://rubytalk.org/t/check-if-file-exists-for-part-of-the-filename/45174/2 "2008-03-14T09:02:07Z")

</div>

Christian Kerth wrote:

> I only want to know if a file exists, that starts with "file\_"

Dir.entries('.').detect {|f| f.match /^file\_/}

Replace '.' with the name of the directory to check if it is not the  
current directory. Will return the name of the first file to match if  
there is one, else will return nil.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![\_Pena\_Botp1](https://avatars.discourse-cdn.com/v4/letter/_/94ad74/32.png) [@\_Pena\_Botp1](https://rubytalk.org/u/_Pena_Botp1)\
**Post date:** [14 March 2008 09:04 UTC](https://rubytalk.org/t/check-if-file-exists-for-part-of-the-filename/45174/3 "2008-03-14T09:04:52Z")

</div>

[[mailto:list-bounce@example.com](mailto:list-bounce@example.com)] On Behalf Of Christian Kerth  
# How do i check if a file exists, that starts with a certain  
# identifier?  
# e.g. Files in Directory  
# file\_1.rb  
# file\_2.rb  
# test\_1.rb  
# I only want to know if a file exists, that starts with "file\_"

there are many ways.  
these are just some...

Dir.glob("file\_\*.rb").empty?  
#=\> false

Dir.glob("file\_\*.rb").size\>0  
#=\> true

Dir.glob("file\_\*.rb")  
#=\> ["file\_1.rb", "file\_2.rb", "file\_3.rb"]

File.exist? "file\_1.rb"  
#=\> true

File.exist? "file\_2.rb"  
#=\> true

File.exist? "file\_4.rb"  
#=\> false

kind regards -botp
