Move files to a target directory using Ruby - ruby

I'm trying to read a file(input.txt) containing file names and move the corresponding files present in the input.txt to the target location (d:/target)
(script, input.txt and the files to be moved are all in the same directory)
below is what I have tried
require 'fileutils'
target = "D://target/"
file='input.txt'
File.readlines(file).each do |line|
puts line
FileUtils.mv(line, target)
end
but Im facing below error and I have checked other options but unable to fix it. Any ideas, thanks.
C:/Ruby23/lib/ruby/2.3.0/fileutils.rb:1329:in `stat': Invalid argument # rb_file
_s_stat - D://targer/north_af.txt (Errno::EINVAL)
input.txt
north_af.txt
south_af.txt
midd_cji.txt
fg_poi.txt
and so on....

I think every line has extra character "\n" at the end. You need to strip it before.
FileUtils.mv(line.strip, target)

Related

No such file or directory # rb_sysopen ruby

Facing below issue eventhough the file is present in the folder.
H:\Ruby_test_works>ruby hurrah.rb
hurrah.rb:7:in `read': No such file or directory # rb_sysopen - H:/Ruby_
test_works/SVNFolders.txt (Errno::ENOENT)
from hurrah.rb:7:in `block in <main>'
from hurrah.rb:4:in `each_line'
from hurrah.rb:4:in `<main>'
Input file (input.txt) Columns are tab separated.
10.3.2.021.asd 10.3.2.041.def SVNFolders.txt
SubversionNotify Subversionweelta post-commit.bat
Commit message still rake customemail.txt
mckechney.com yahoo.in ReadMe.txt
Code :
dir = 'H:/Ruby_test_works'
file = File.open("#{dir}/input.txt", "r")
file.each_line do |line|
initial, final, file_name = line.split("\t")
#puts file_name
old_value = File.read("#{dir}/#{file_name}")
replace = old_value.gsub( /#{Regexp.escape(initial)}, #{Regexp.escape(final)}/)
File.open("#{dir}/#{file_name}", "w") { |fi| fi.puts replace }
end
I have tried using both forward and backward slashes but no luck. What I'm missing, not sure. Thanks.
puts file_name gives the below values
SVNFolders.txt
post-commit.bat
customemail.txt
ReadMe.txt
The file_name contains the newline character \n at the end, which won't get printed but messes up the path. You can fix the issue by stripping the line first:
initial, final, file_name = line.strip.split("\t")
When debugging code, be careful with puts. Quoting its documentation reveals an ugly truth:
Writes the given object(s) to ios. Writes a newline after any that do not already end with a newline sequence.
Another way to put this is to say it ignores (potential) newlines at the end of the object(s). Which is why you never saw that the file name actually was SVNFolders.txt\n.
Instead of using puts, you can use p when troubleshooting issues. The very short comparison between the two is that puts calls to_s and adds a newline, while p calls inspect on the object. Here is a bit more details about the differences: http://www.garethrees.co.uk/2013/05/04/p-vs-puts-vs-print-in-ruby/
Sometimes the issue is not the file, but the path to the file. Consider compare the file path with what you think the file path is with something like:
File.expand_path('my_file.rb')

Opening a Text File in Ruby

I am trying to create a program that will count the word frequency within a text file that I have created. I have a text file titled moms_letter.txt and this is my code:
word_count = {}
File.open("moms_letter.txt", "r") do |f|
f.each_line do |line|
words = line.split(' ').each do |word|
word_count[word] += 1 if word_count.has_key? word
word_count[word] = 1 if not word_count.has_key? word
end
end
end
puts word_count
The problem I am getting is when I go to run the file, I get the error:
there is no such file or directory - moms_letter.txt (Errno: : ENOENT)
Not quite sure why this is occurring when I have the text file created.
Any help is appreciated.
I am also newbie in Ruby, so thanks for the patience.
You must be executing your program from outside the directory where your moms_letter.txt file resides. You need to use an absolute path to open your file. Or, execute your program always from the directory where the .txt is. So, instead of using "moms_letter.txt" go with "complete/path/to/file/moms_letter.txt".
I'm fairly new to Ruby too, but have worked with text files a bit recently. It may seem like an obvious question, but is the text file you're trying to open in the same directory as your .rb file? Otherwise you'll need to include the relative path to it.
For troubleshooting sake, try File.new("temp.txt", "w") and then File.open("temp.txt", "r") to see if that works. Then you'll know if it's an issue with your code or with the txt file you're trying to access.
Also using File.exists?("moms_letter.txt") will help you determine whether you can access that file from within your .rb script.
Hope that helps!

Ruby find a line in a file and add below it

I have a text file that I need to edit in a chef recipe.
I need to find this particular line (in bold), and insert configuration below it.
.
.
.
# PLACE YOUR CONFIGURATION MEMORY start up here :
<INSERT MEMORY ARGUMENTS HERE>
.
.
.
.
Here is what I have been trying..I just would like to know is there some sort of functionality in Ruby
where I could find a line and then below that line add new entry?
ruby_block "edit the configuration file " do
block do
text = File.read(file_name)
replace = text.sub(/# PLACE YOUR CONFIGURATION MEMORY start up here :/, "MEM_ARGS=-Xms512m -Xmx1024m");
File.write(file_name, replace)
end
end
I don't want to replace the comment section though, I just want to make use of it as an anchor where I could add new lines of text.
The correct-er way to do this in Chef is the line cookbook, which has resources for managing this kind of in-place file manipulation. However, we strongly recommend against using it as it is very easy to write a bad regex or whatnot and up with a non-convergent system. Managing the whole file with a template resource is preferred.
Try this
File.open('input') do |i|
File.open('output', 'w') do |o|
while line = i.gets
o.puts line
if line.chomp == "# PLACE YOUR CONFIGURATION MEMORY start up here:"
o.puts "MEM_ARGS=-Xms512m -Xmx1024m"
end
end
end
end
`mv output input`
How does this work?
First open the input file, will fail with Errno::ENOENT if it does not exist
Then open the output file
Streams through them line by line
Inserts additional lines after marker line, chomp removes trailing linebreak
The do end blocks automagically close both files
Eventually replaces input with mv

Ruby saying file doesnt exist

I'm new to Ruby, and I am writing a test program just to get some of the features down. Here is the program
#!/usr/bin/env ruby
class FileManager
def read_file(filename)
return nil unless File.exist?(filename)
File.read(filename)
end
end
if __FILE__ == $0
fm = FileManager.new
puts "What file would you like to open?"
fname = gets
puts fm.read_file fname
end
As you can see, it is very simple. If I comment the first line of the read_file method, I get this error
No such file or directory - /Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text (Errno::ENOENT)
from /Users/macuser/Projects/Aptana Studio 3 Workspace/Ruby Test/ruby.rb:6:in `read_file'
from /Users/macuser/Projects/Aptana Studio 3 Workspace/Ruby Test/ruby.rb:15:in `<main>'
when I run the program and use this file: /Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text
However, if I run cat /Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text, it outputs Hello, world!, as it should.
I don't believe it's a permissions issue because I own the folder, but just in case I've tried running the program as root. Also, I have made sure that fname is the actual name of the file, not nil. I've tried both escaped and unescaped versions of the path, along with just text or the full path. I know for a fact the file exists, so why is Ruby giving me this error?
With gets filename the filename includes a newline \n.
You have to remove it in your filename:
gets filename
p filename #"test.rb\n"
p File.exist?(filename) #false
p File.exist?(filename.chomp) #true
(And you don't need to mask the spaces)
It looks like you're shell-escaping your spaces even though gets does not go through a shell. You want to enter "/Users/macuser/Projects/Aptana Studio 3 Workspace/Ruby Test/text" instead of "/Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text".

ERRNO::EACCES in String substitution

I'm trying to write a program which substitutes a string.
require File.join(APP_ROOT, 'lib', 'main.rb')
files_names = Dir.entries("../DeSpacer")
files_names.each do |file_name|
File.open("#{file_name}", "w") do |text|
text.each {|line| line.gsub!(/\.\s{2,}/, "\.\s")}
end
end
I keep getting a
Permission denied -. (ERRNO::EACCES)
Can you explain what I am doing wrong?
The initial problem is that you're only opening the file for writing ('w'), and not reading, and thus receiving the exception.
As the comments above mention, there are other issues with the code as well.
This answer gives a more typical way to do what you're trying to do.
As mentioned in another answer to the same question, Ruby also has a command line shortcut inherited from Perl which makes things like this trivial:
ruby -pi.bak -e "gsub(/oldtext/, 'newtext')" *.txt
This will edit a file or files in place, backing up the previous version with a suffix of '.bak'.
From Programming Ruby:
-i [extension}
' Edits ARGV files in place. For each file named in ARGV, anything you write to
standard output will be saved back as the contents of that file. A backup copy of
the file will be made if extension is supplied.
% ruby -pi.bak -e "gsub(/Perl/, 'Ruby')" *.txt

Resources