0

I have a script where I iterate through some directories and create files there and put some strings inside the created files. Within the directories where I create my files, there exist some other files which I would like to open and search for some specific strings to copy them into my created files. This existing files have the ".sln" extension .

Is there an easy way to tell Ruby just in that moment when I create my file, to open the existing .sln file and to parse it. I imagine something like:

File.open('*.sln', 'r')

I have tried something like this:

sln_files = Dir.glob('*.sln', 'r')
File.open(sln_files)

and also this method:

Dir["/path/to/search/**/*.sln"]

but it gives me the full path to the file. I need only the file names

Any idea? I would like to have the possibility to use wildcards within the File.open method

So I found the solution at an already existing topic (Get names of all files from a folder with Ruby). It was:

files = Dir["/work/myfolder/**/*.txt"]

files.each do |file_name|
  if !File.directory? file_name
    puts file_name
    File.open(file_name) do |f|
      f.each_line do |line|
        if line =~ /banco1/
          puts "Found: #{line}"
        end
      end
    end
  end
end
JohnDoe
  • 825
  • 1
  • 13
  • 31
  • You can't use wildcards like that. Ruby, along with every other language I've ever worked with, expects an explicit file name. If there are multiple files to process we get those names and loop over them. If we don't know the basename of the file, only the extension, we have to search for files matching that extension, or pattern, then iterate over the resulting array. – the Tin Man Nov 12 '15 at 19:18
  • @theTinMan It's a typical use-case to me. For example if you files have timestamps, you need some kind of wildcards. – sschmeck Nov 12 '15 at 19:26
  • If you have a full pathname to a file, then you should use `File.basename` to extract just the filename.ext. But, really, this is all well documented in [File](http://ruby-doc.org/core-2.2.3/File.html) and covered many times here on Stack Overflow and the internet. – the Tin Man Nov 12 '15 at 19:26
  • The use-case may be, but the code to process it will still require doing something besides passing a wildcard to `open`. – the Tin Man Nov 12 '15 at 19:27
  • It covers the part of the question that deals with handling wildcards. The part about opening files is obviously covered since `File.open` is cited. – the Tin Man Nov 12 '15 at 19:46

1 Answers1

2

One solution could be ..

Dir.glob('*.sln').each do |filename|
  File.open(filename, 'r') do |file|
    # reading ...
  end
end

If you want only the first file or you are sure there is only one file you could create a helper method.

def with_open_file(pattern)
  filename = Dir.glob('*.sln').first
  File.open(filename, 'r') { |f| yield(f) }
end

with_open_file('*.sln') do |file|
  # reading ...
end
sschmeck
  • 7,233
  • 4
  • 40
  • 67