0

I want to remove the following characters from several files in a folder. What I have so far is this:

str.delete! '!@#$%^&*() 

which I think will work to remove the characters. What do I need to do to make it run through all the files in the folder?

sawa
  • 165,429
  • 45
  • 277
  • 381
  • What do you want to do with the output? If you do not do anything with it, the replaced strings will disappear in place. – sawa Mar 18 '14 at 18:03
  • 1
    Do you want to remove those characters from the filename or from the content of the files (in case they are text files)? – Daniël Knippers Mar 18 '14 at 18:08
  • I want to remove them from the content of the files. Basically, I just need it to run through all the files in a directory, removing any instances of those characters from all the files, and then leaving the name of the file the same. – user3434301 Mar 18 '14 at 18:23

3 Answers3

0

I think this might work, although I'm a little shaky on the Dir class in Ruby.

Dir.foreach('/path/to/dir') do |file|
  file.delete '!@#$%^&*() 
end

There's a more general version of your question here: Iterate through every file in one directory

Hopefully a more thorough answer will be forthcoming but maybe this'll get you where you need.

Community
  • 1
  • 1
  • Eh, the `file` variable is just a String here; the filename of the file. Calling `.delete` removes the specified characters from the filename String. It leaves the actual filename unchanged, however. That would require you to *rename* the file. Neither does this remove those characters from the content of the file (I'm not sure what's supposed to happen, the question is unclear). – Daniël Knippers Mar 18 '14 at 18:10
  • So basically I want to leave the filenames alone, just remove the specified characters from within the actual files. Sorry if this wasn't clear. – user3434301 Mar 18 '14 at 18:22
0

You clarified your question, stating you want to remove certain characters from the contents of files in a directory. I created a straight forward way to traverse a directory (and optionally, subdirectories) and remove specified characters from the file contents. I used String#delete like you started with. If you want to remove more advanced patterns you might want to change it to String#gsub with regular expressions.

The example below will traverse a tmp directory (and all subdirectories) relative to the current working directory and remove all occurrences of !, $, and @ inside the files found. You can of course also pass the absolute path, e.g., C:/some/dir. Notice I do not filter on files, I assume it's all text files in there. You can of course add a file extension check if you wish.

def replace_in_files(dir, chars, subdirs=true)
  Dir[dir + '/*'].each do |file|
    if File.directory?(file) # Traverse inner directories if subdirs == true
      replace_in_files(file, chars, subdirs) if subdirs
    else # Replace file contents
      replaced = File.read(file).delete(chars)
      File.write(file, replaced)
    end
  end
end

replace_in_files('tmp', '!$@')
Daniël Knippers
  • 3,049
  • 1
  • 11
  • 17
  • Hello, thank you for your response. For some reason, I cannot get this working. Do I just place the script in the same directory as the text files I want it to change and run it? Or do I need to create an absolute path. Sorry I need some more help :( – user3434301 Mar 20 '14 at 14:37
  • @user3434301 You can place the script anywhere, and you can use either an absolute path as the argument (for example: `"C:/users/yourname/desktop/folder"`) or a relative path (e.g., `"folder"` if you placed the script on your desktop and 'folder' is a folder on your desktop). Do not place it in the same directory, then it will also replace characters inside the script source file :) Just place it in the parent directory (e.g., if your file is in C:/data/files, place the script in C:/data and call it with 'files' as first argument). – Daniël Knippers Mar 20 '14 at 14:41
  • Hello Daniël, thank you again for the response. I changed every instance of dir in the script to the name of the folder (TestX) and it throws an error. Am I supposed to change something besides dir in the script? I just put the name of the folder in double quotes "TextX" and I get the following error: syntax error, unexpected ',', expecting end-of-input def replace_in_files("TextX", chars, subdirs=true) – user3434301 Mar 20 '14 at 16:22
  • What? Omg no. You only have to replace the `'tmp'` on the very last line... So if you placed the script in `C:/data`, and you have a folder `C:/data/files` with text files, you replace `'tmp'` by `'files'` and run the script (which you place in `C:/data`). – Daniël Knippers Mar 20 '14 at 16:29
0
Dir.foreach('filepath') do |f|
    next if Dir.exists?(f)
    file = File.new("filepath/#{f}",'r+')
    text = file.read.delete("'!@#$%^&*()")
    file.rewind
    file.write(text)
    file.close
end

The reason you can't do

file.write(file.read.delete("'!@#$%^&*()"))

is that file.read leaves the "cursor" at the end of the text. Instead of writing over the file, you would be appending to the file, which isn't what you want.

You could also add a method to the File class that would move the cursor to the beginning of the file.

class File
    def newRead
        data = self.read
        self.rewind
        data
    end
end

Dir.foreach('filepath') do |f|
    next if Dir.exists?(f)
    file = File.new("filepath/#{f}",'r+')
    file.write(file.newRead.delete("'!@#$%^&*()"))
    file.close
end
JordanD
  • 163
  • 6
  • Hey Jordan, thanks for the response. I was trying to use the following code: `Dir.foreach('filepath') do |f| next if Dir.exists?(f) file = File.new("filepath/#{f}",'r+') text = file.read.delete("'!@#$%^&*()") file.rewind file.write(text) file.close end` I added the filepath to dir.foreach but its throwing errors when I add it to file.new. Is it supposed to look like this? `file = File.new("\Users\Tim\Test/#{f}", 'r+')` or am I doing something wrong? I'm using win7 – user3434301 Mar 20 '14 at 14:41
  • In file paths, use '/', not '\'. Also, make sure that your ruby file is in a different directory than the directory in which you are deleting characters. Hope that helps – JordanD Mar 20 '14 at 18:12