replace a text in base directory

P

Pokkai Dokkai

how can replace a text from all files in
"/home/user" directory and sub directories (tree)...
 
7

7stud --

Pokkai said:
how can replace a text from all files in
"/home/user" directory and sub directories (tree)...

Try this:

Dir.glob('/Users/me/2testing/dir2/**/*') do |fname|
next if File.directory?(fname)

File.open("temp.txt", "w") do |temp_file|
IO.foreach(fname) do |line| #fname is from outer loop
new_line = line.gsub("hello world", "goodbye")
temp_file.print(new_line)
end

File.delete(fname)
File.rename("temp.txt", fname)
end
end


** means to look in the current directory and all subdirectories for
the filenames *, where * means all file names(including directory
names).
 
W

William James

Try this:

Dir.glob('/Users/me/2testing/dir2/**/*') do |fname|
next if File.directory?(fname)

File.open("temp.txt", "w") do |temp_file|
IO.foreach(fname) do |line| #fname is from outer loop
new_line = line.gsub("hello world", "goodbye")
temp_file.print(new_line)
end

File.delete(fname)
File.rename("temp.txt", fname)
end
end

This botched code bombs. Don't ever post untest code without
stating that it is untested code.
 
S

Suraj Kurapati

Pokkai said:
how can replace a text from all files in
"/home/user" directory and sub directories (tree)...

Using a little UNIX magic, you can get away with a shorter solution:

find /home/user -type f -print0 | xargs -0 \
ruby -pe 'gsub /pattern/, "replacement"' -i.bak

The "-i" will modify the file in-place and the ".bak" after it will make
a backup of the original file with a ".bak" suffix.

You could also use sed, awk, perl, etc. in place of 'ruby' in the same
command.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,268
Messages
2,571,344
Members
48,019
Latest member
Migration_Expert

Latest Threads

Top