Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 script
Index -> General Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
bugzpodder




PostPosted: 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?
Sponsor
Sponsor
Sponsor
sponsor
Martin




PostPosted: Mon Jan 03, 2005 2:41 pm   Post subject: (No 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.
rizzix




PostPosted: Mon Jan 03, 2005 3:08 pm   Post subject: (No subject)

perl.
wtd




PostPosted: Mon Jan 03, 2005 3:24 pm   Post subject: (No subject)

rizzix wrote:
perl.


More specifically, eat your Perl pie.

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




PostPosted: Mon Jan 03, 2005 3:24 pm   Post subject: (No subject)

mmmmm pie.
wtd




PostPosted: Mon Jan 03, 2005 3:35 pm   Post subject: (No 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
md




PostPosted: Tue Jan 11, 2005 3:12 pm   Post subject: (No subject)

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




PostPosted: Tue Jan 11, 2005 3:14 pm   Post subject: (No subject)

Sorry, I was high on crack when I wrote that.
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> General Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 8 Posts ]
Jump to:   


Style:  
Search: