I have developed a system where a specific user has access to search for a specific file. The problem is that this file is in a folder so I am having a hard time coding it.
My method must be able to find my keyword input in the file name.
For example, If I search for Bob, I will get all the files where Bob are included in the filename
def search_user(search)
keyword = File.readlines('test3.yml')
matches = keyword.select { |username| username[/#{search}/] }
if File.read("test3.yml").include?(search)
puts "_____________________________________________"
puts ("Search results for student: " + search + ":") #
puts
puts matches
puts "_____________________________________________"
else #If not it will give the user feedback that its not there
puts "_____________________________________________"
puts
puts ("Sorry, we couldnt find #{search} in the system.")
puts "_____________________________________________"
end
end
Related
Ruby Beginner.
Learning to write to files, in a directory. Wondering how to now read those files from a directory? Assume there's a directory "book_test" with some .txt files, with a line of text in each file.
puts "Enter name:"
name = gets.strip
filename = "#{name}.txt"
puts "Enter number:"
number = gets.strip
number_in_file = "#{number}"
File.write("/Users/realfauxreal/book_test/#{filename}", number_in_file)
so far so good. I can add a bunch of .txt files with some numbers (or whatever) in them, to the "book_test" dir.
Now If I want to retrieve them, obviously this doesn't work.
Dir.open "/Users/realfauxreal/book_test" do |dir|
dir.each do |name, number|
puts "#{name}, #{number}"
end
end
Am I on the right track? Obviously this isn't outputting properly, plus there are some additional files that I don't want to show up. Is this a case for the .glob helper?
If I'm way off base, any tips would be appreciated.
Using Dir::[], File::basename and File::read
Dir['/Users/realfauxreal/book_test/*.txt'].each do |file_path|
p "#{File.basename(file_path)}, #{File.read(file_path)}"
end
"foo.txt, 2"
=> ["book_test/foo.txt"]
I'm reading user ids, say ncr\yui30n, from a file and checking if that user id is present in any of the file or files , if present delete it.I'm able to do that with my code below.
svn_files = Dir.glob("E:\nano\*_access.txt")
value=File.open('E\new_dir\access_list.txt').read
value.each_line do |line|
line.chomp!
print "Z ID: #{line}\n"
svn_files.each do |file_name|
print "checking in file:#{file_name}\n"
text = File.read(file_name)
replace = text.gsub( /#{Regexp.escape(line)}\,\s/, '' )
File.open(file_name, "w") { |file| file.puts replace }
end
end
what I'm trying to expand with my code is, to capture the string, say (ncr\yui30n) deleted from which file or files and from which pool that string is associated in that particular file to an output log file.
Eg. E:\nano\ids_access.txt
# Digital created on July 2016
# Digital Owner: John Cena (jxcgo)
# Digital access: create delete access
[pool]
#rem = ncr\abc_efg_dev, ncr\abc_efg_test, ncr\jx8go5, ncr\atxe5t
#digital_owner = ncr\yui30n, ncr\bhyrl4
I'm trying to create output log file in below pattern
Removed_users.log
Removed user : ncr\yui30n
Removed from : ids_access.txt (if present in multiple files record that too)
Pool : #digital_owner
I can only come with the below piece of snippet, inside the 2nd loop :
File.open("E:\Removed_users.log", "a") { |log|
log.puts "Removed from: #{file_name}"
log.puts "Removed user : #{line}"
log.puts "*" * 50
}
issues is, its recording every access file its searching but I want to capture only the file from where the string is deleted and I'm not sure how to get the pool name too, say #digital_owner in the below example.
Any suggestions please . Thanks. I'm very new to ruby and still in learning phase so please excuse if its simple question.
You can add your code in an if or unless statement, comparing text vs replace to see if any change (i.e. a replacement) was made; something like this:
svn_files = Dir.glob("E:\nano\*_access.txt")
value=File.open('E\new_dir\access_list.txt').read
value.each_line do |line|
line.chomp!
print "Z ID: #{line}\n"
svn_files.each do |file_name|
print "checking in file:#{file_name}\n"
text = File.read(file_name)
replace = text.gsub( /#{Regexp.escape(line)}\,\s/, '' )
unless text == replace
File.open("E:\Removed_users.log", "a") { |log|
log.puts "Removed from: #{file_name}"
log.puts "Removed user : #{line}"
log.puts "*" * 50
}
File.open(file_name, "w") { |file| file.puts replace }
end
end
end
And since you are already making that comparison, its a good idea to include your file update in that statement too.
Not related to your question, but you code simplify your code changing this line:
File.open(file_name, "w") { |file| file.puts replace }
to:
File.write(file_name, replace)
I have 385 subfolders in a directory, each containing a CSV file along with several pdfs. I'm trying to find a way to go through each subfolder and write a list of the pdfs to a txt file. (I realize there are better languages out there to do this than Ruby, but I'm new to programming and it's the only language I know.)
I have code that gets the job done, but the problem I'm running into is it's listing the subfolder directory as well. Example: Instead of writing "document.pdf" to a text file, it's writing "subfolder/document.pdf."
Can someone please show me how to write just the pdf filename?
Thanks in advance! Here's my code:
class Account
attr_reader :account_name, :account_acronym, :account_series
attr_accessor :account_directory
def initialize
#account_name = account_name
#account_series = account_series
#account_directory = account_directory
end
#prompts user for account name and record series so it can create the directory
def validation_account
print "What account?"
account_name = gets.chomp
print "What Record Series? "
account_series = gets.chomp
account_directory = "c:/Processed Batches Clone/" + account_name + "/" + account_series + "/Data"
puts account_directory
return account_directory
end
end
processed_batches_dir = Account.new
#changes pwd to account directory
Dir.chdir "#{processed_batches_dir.validation_account}"
# pdf list
processed_docs = []
# iterates through subfolders and creates list
Dir.glob("**/*.pdf") { |file|
processed_docs.push(file)
}
# writes list to .txt file
File.open("processed_batches.txt","w") { |file|
file.puts(processed_docs)
}
There may be a better way, but you could always split on the last slash in the path:
Dir.glob('**/*.pdf').each do |file_with_path|
processed_docs.push(file_with_path.split('/').last)
end
i am new to programming in ruby, and i am trying to get the value of json['earning_rate_hr'] but i get an error, in '[]': no implicit conversion of String into Integer (TypeError)
i know and i understand the error, however this is not my main question here is my file :
checkingchecker.rb :
#require_relative '../lib/hackex/net/typhoeus'
require_relative '../lib/hackex'
require 'rubygems'
require 'json'
file = 'accounts1.txt'
f = File.open file, 'r'
puts "MADE BY THE PEOPLE, FOR THE PEOPLE #madebylorax"
puts ""
puts "--------------------------------------------------------"
puts ""
while line = f.gets
line = line.chomp.split(';')
email, password = line
puts "logging in as " + email
HackEx.LoginDo(email, password) do |http, auth_token, user|
puts "getting info..."
user = HackEx::Request.Do(http, HackEx::Request.UserInfo(auth_token))['user']
puts "receieved user info!"
bank = HackEx::Request.Do(http, HackEx::Request.UserBank(auth_token))['user_bank']
puts "recieved bank info!"
json = HackEx::Request.Do(http, HackEx::Request.UserSpam(auth_token))['spam']
puts "recieved spam info!"
puts json['earning_rate_hr'] #error line, the error is because this is an array, and it cant be turned into integer, i was wondering if there is a way to use puts on it without trying to make it an integer
userchecking = bank["checking"]
checking = userchecking.scan(/.{1,3}/).join(',')
puts email + " has in Checking: BTC #{checking}"
puts ""
puts "--------------------------------------------------------"
puts ""
end
end
i tried to do puts json, it puts items like this one :
{"id"=>"9867351", "user_id"=>"289108", "victim_user_id"=>"1512021",
"victim_ip"=
"86.60.226.175", "spam_level"=>"50", "earning_rate_hr"=>"24300", "total_earning s"=>"13267800", "started_at"=>"2015-11-01 07:46:59",
"last_collected_at"=>"2015- 11-24 01:46:59"}
what i want to do is select the earning_rate_hr for each one of them and add them together, however i do not have a clue on how to do that, since the error is not fixed and i cant get the value of it
ps : i tried turning it into a Hash, and i also tried using .first, but .first only shows the firs one, i want to show all of them, thank you
I know you from line messenger, I haven't used ruby codes in a long time and this one keeps giving me cloudflare errors, I'm not sure if its because of server downtime/maintainance or whatever but yeah anyway heres your script, enjoy farming ;) -LineOne
PS, I changed a few strings to make it look a lil cleaner so you can see the spam income easier, and added the sleep (1) because sleeping for one second before reconnecting helps to prevent cloudflare errors
also you don't need to require json or rubygems in your hackex scripts because its required in the library so its all covered pre-user-input/script
require_relative 'libv5/lib/hackex'
while 1<2
begin
print'Filename: '
fn=gets.chomp
file = fn+'.txt'
f = File.open file, 'r'
puts "MADE BY THE PEOPLE, FOR THE PEOPLE #madebylorax" #helped by lineone
puts ""
puts "--------------------------------------------------------"
puts ""
while line = f.gets
line = line.chomp.split(';')
email, password = line
HackEx.LoginDo(email, password) do |http, auth_token, user|
puts "Retrieving Info..."
puts''
user = HackEx::Request.Do(http, HackEx::Request.UserInfo(auth_token))['user']
bank = HackEx::Request.Do(http, HackEx::Request.UserBank(auth_token))['user_bank']
json = HackEx::Request.Do(http, HackEx::Request.UserSpam(auth_token))['spam']
cash_count=0
tot_count=0
json.each do |j|
earn_rate = j['earning_rate_hr']
total= j['total_earnings']
cash_count+=earn_rate.to_i
tot_count+=total.to_i
end
print "#{email}: current earnings: #{cash_count} per hour, Total earnings #{tot_count},"
userchecking = bank["checking"]
checking = userchecking.scan(/.{1,3}/).join(',')
puts " #{checking} BTC in Checking"
puts ""
puts "--------------------------------------------------------"
puts ""
sleep 1
end
end
rescue
puts"#{$!}"
end
end
Thats fine you can also calculate the total income of your farms by adding new variables at the top example a=0 then adding the number at the end a+=tot_count
This should help:
earning_rates = json.map{|e| e["earning_rate_hr"]}
puts "Earning rates per hour: #{earning_rates.join(" ")}"
puts "Sum of earning rates: #{earning_rates.map{|e| e.to_i}.inject{|sum, x| sum + x}}"
I'm following a tutorial and am trying to change the names of three files in a folder that's located under 'drive/users/myname/test'. I'm getting the error:
'chdir': No such file or directory - test'.
The starting path is already 'drive/users/myname', which is why I thought that I only had to enter 'test' for Dir.chdir.
How do I correctly input the paths on Mac OS?
Dir.chdir('test')
pic_names = Dir['test.{JPG,jpg}']
puts "What do you want to call this batch"
batch_name = gets.chomp
puts
print "Downloading #{pic_names.length} files: "
pic_number = 1
pic_names.each do |p|
print '.'
new_name = "batch_name#{pic_number}.jpg"
File.rename(name, new_name)
pic_number += 1
end
I think you have to provide the absolute path. So, your first line should be:
Dir.chdir("/drive/users/myname/test")
According to the documentation:
Dir.chdir("/var/spool/mail")
puts Dir.pwd
should output/var/spool/mail.
You can look at the documentation for more examples.
In:
File.rename(name, new_name)
name is never defined prior to its attempted use.
Perhaps p is supposed to be name, or name should be p?
With that assumption I'd write the loop something like:
pic_names.each_with_index do |name, pic_number|
print '.'
new_name = "#{ batch_name }#{ 1 + pic_number }.jpg"
File.rename(name, File.join(File.dirname(name), new_name))
end
File.join(File.dirname(name), new_name) is important. You have to refer to the same path in both the original and new filenames, otherwise the file will be moved to a new location, which would be wherever the current-working-directory points to. That's currently masked by your use of chdir at the start, but, without that, you'd wonder where your files went.