0

I got a folder with the following zip files :

13162.zip 14864.zip 19573.zip 20198.zip

In console, when i run :

cd my_folder; echo `ls *{.zip,.ZIP}`

I got the following output (which is perfect) :

ls: cannot access *.ZIP: No such file or directory
13162.zip 14864.zip 19573.zip 20198.zip

Now when in ruby i try the same :

cmd= "cd my_folder; echo `ls {*.zip,*.ZIP}`";
puts `#{cmd}`

It only display :

ls: cannot access {*.zip,*.ZIP}: No such file or directory
 => nil

I try this solution : Getting output of system() calls in Ruby

But it seem not work in my case.

How can i get the same output in ruby and in shell ?

Naremy
  • 491
  • 8
  • 22
  • 1
    In `irb` console type `cmd = \`cd Downloads; ls *.zip *.ZIP\`` followed by `puts cmd` – Imran Ali Jan 09 '17 at 11:49
  • What do you want to achive? Your code isn't valid ruby code. Please, provide correct code. – Yevgeniy Anfilofyev Jan 09 '17 at 11:53
  • Have you considered using Ruby methods like [`Dir.chdir`](http://ruby-doc.org/core-2.4.0/Dir.html#method-c-chdir) and [`Dir.glob`](http://ruby-doc.org/core-2.4.0/Dir.html#method-c-glob)? – Stefan Jan 09 '17 at 12:49
  • Imran Ali : Solve my concern! Thx. (Dir.chdir => With the existing codebase i have to work to, it's not possible but it's of course a better idea) – Naremy Jan 09 '17 at 13:06
  • 1
    You're using brace expansion. This is supported by your interactive shell (bash), but not by your system shell (probably dash) which ruby uses. You should write this in Ruby instead of using a shell, and @EricDuminil shows how. You could technically have used the sh equivalent `ls *.zip *.ZIP` or commonly `ls *.[zZ][iI][pP]` but Eric's answer is much better. – that other guy Jan 09 '17 at 18:54

2 Answers2

2

Ruby Only

You can use Dir.glob with File::FNM_CASEFOLD for case-insensitive search :

Dir.chdir 'my_folder' do
  Dir.glob('*.zip', File::FNM_CASEFOLD).each do |zip_file|
    puts zip_file
  end
end

#=> 
# 19573.zip
# 13162.zip
# 14864.zip
# 20198.zip
# 12345.zIp

Ruby + bash

You can use find for case-insensitive search :

paths = `find my_folder -maxdepth 1 -iname '*.zip'`.split
#=> ["my_folder/19573.zip", "my_folder/13162.zip", "my_folder/14864.zip", "my_folder/20198.zip", "my_folder/12345.zIp"]

-printf '%P' can also be used to only display the filenames :

files = `find my_folder -maxdepth 1 -iname '*.zip' -printf '%P\n'`.split
#=> ["19573.zip", "13162.zip", "14864.zip", "20198.zip", "12345.zIp"]
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
0

I think this should work directly on the terminal:

echo 'system("ls *ZIP,*zip")' | ruby

or create a ruby file with the following contents

system("cd my_folder; ls {*.zip,*.ZIP}")

and then execute it. Once you write ls, you don't need echo!

Karan Shah
  • 1,304
  • 11
  • 15