
-----------------------------------
bugzpodder
Mon Jan 03, 2005 10:06 am

script
-----------------------------------
i want to write some kind of script or program that basically opens a text file, searches for a line, if it exists, change it.  whats the best way to do this?

-----------------------------------
Martin
Mon Jan 03, 2005 2:41 pm


-----------------------------------
As in a unix shell script?

You could write a quick C++ program I imagine.

#include 
using namespace std;

int main (int argc, char *argv[] ) {
     for (int i = 1; i < argc; i++) //Since argv[0] is the program's name
          searchandreplace(*argv[i]);
     return 0;
}

You would then run the program as "this.exe -text.txt -text2.txt -text3.txt" etc.

-----------------------------------
rizzix
Mon Jan 03, 2005 3:08 pm


-----------------------------------
perl.

-----------------------------------
wtd
Mon Jan 03, 2005 3:24 pm


-----------------------------------
perl.

More specifically, eat your Perl pie.

perl -p -i.bak -e "s/search/replace/" file1 file2 fileN

-----------------------------------
rizzix
Mon Jan 03, 2005 3:24 pm


-----------------------------------
mmmmm pie.

-----------------------------------
wtd
Mon Jan 03, 2005 3:35 pm


-----------------------------------
Works with Ruby too, and more powerfully, too.

Here's the basic conversion:

ruby -p -i.bak -e "$_.gsub! /search/, 'replace'" file.txt

Now, let's say I want a count of how many replacements were made.

ruby -p -i.bak -e "BEGIN{$c=0};END{$stderr.puts $c};$_.gsub! /search/ do $c += 1;'replace' end" file1 file2 fileN

-----------------------------------
md
Tue Jan 11, 2005 3:12 pm


-----------------------------------
martin, your program should be passes text1.txt, not -text1.txt unless the file is called -text1.txt :P

-----------------------------------
Martin
Tue Jan 11, 2005 3:14 pm


-----------------------------------
Sorry, I was high on crack when I wrote that.
