Computer Science Canada

script

Author:  bugzpodder [ Mon Jan 03, 2005 10:06 am ]
Post subject:  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?

Author:  Martin [ Mon Jan 03, 2005 2:41 pm ]
Post subject: 

As in a unix shell script?

You could write a quick C++ program I imagine.

code:
#include <fstream>
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.

Author:  rizzix [ Mon Jan 03, 2005 3:08 pm ]
Post subject: 

perl.

Author:  wtd [ Mon Jan 03, 2005 3:24 pm ]
Post subject: 

rizzix wrote:
perl.


More specifically, eat your Perl pie.

code:
perl -p -i.bak -e "s/search/replace/" file1 file2 fileN

Author:  rizzix [ Mon Jan 03, 2005 3:24 pm ]
Post subject: 

mmmmm pie.

Author:  wtd [ Mon Jan 03, 2005 3:35 pm ]
Post subject: 

Works with Ruby too, and more powerfully, too.

Here's the basic conversion:

code:
ruby -p -i.bak -e "$_.gsub! /search/, 'replace'" file.txt


Now, let's say I want a count of how many replacements were made.

code:
ruby -p -i.bak -e "BEGIN{$c=0};END{$stderr.puts $c};$_.gsub! /search/ do $c += 1;'replace' end" file1 file2 fileN

Author:  md [ Tue Jan 11, 2005 3:12 pm ]
Post subject: 

martin, your program should be passes text1.txt, not -text1.txt unless the file is called -text1.txt Razz

Author:  Martin [ Tue Jan 11, 2005 3:14 pm ]
Post subject: 

Sorry, I was high on crack when I wrote that.


: