Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search and replace

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi, I have a simple question.

Can anyone tell med how to replace some words in a text file ?

The text file looks like this

Hej du glade, jag hoppas att jag kommer att fa ett bra och trevligt svar i denna utmarka konferans

And I want to replace hoppas with hello or what ever and the write it back som it will looks like this

Hej du glade, jag hello att jag kommer att fa ett bra och trevligt svar i denna utmarka konferans


Thanks in advance :)

 
Something like this should work:

#!/usr/bin/perl -w
# Assume program name is PROGA

while <STDIN> {
s/hoppas/hello/g;
print &quot;$_&quot;;
}
exit;


To execute you would use:

PROGA <inputfilename >outputfilename

of in MSDOS:

perl PROGA <inputfilename >outputfilename

Hope this helps (somewhat).



 
Hi and thanks.
But I must run in in a script, there will be no command line options.

The file must be a value like
$newfile = &quot;Myfile.txt&quot;;

Maybe you know this one to ??

Thanks :)
 
Hejsan. This code should work:
#!/usr/bin/perl -w
my $file = &quot;File.txt&quot;;
my $search = &quot;hoppas&quot;;
my $replace = &quot;hello&quot;;
open (FILE, &quot;<$file&quot;);
my @content = <FILE>;
close (FILE);
open (FILE &quot;>$file&quot;);
foreach my $line (@content)
{
$line =~ s/$search/$replace/gi;
print FILE $line;
}
close (FILE);
exit; //Daniel
 
ok, i understand this

$line =~ s/$search/$replace/

and i know &quot;i&quot; means case sensative,(i hope lol), but i have never quite grasped what &quot;g&quot; does. any explanations?
 
There are several of the pattern modifiers, a few being:

i - ignore alphabetic case
x - ignore white space in pattern and allow comments
g - globally perform all possible operations
s - let . character match newlines

The g simply means match every occurrance of the search pattern.

eg:

$line = &quot;1200012000012&quot;;
$line =~ s/12/XX/g;

will result in $line equalling &quot;XX000XX0000XX&quot;.

HTH,
Barbie.
Leader of Birmingham Perl Mongers
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top