[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] A basic question.



>Second can anyone tell me where to find a basic 
>example script that opens a text file, finds and  replaces some text, and 
>saves a copy under another name? Thanks.
>
>
>Regards,
>
>Eric Mings Ph.D.

#!/usr/bin/perl

# The file to search.
$text_file = "/path/to/text_file.text";

# The new file with the replaced string.
$new_text_file = "/path/to/new_text_file.text";

# Open for reading.
open (FILE, "$text_file");
# Open for writing.
open (NEWFILE, ">$new_text_file");

# Each line is an array element.
@text = <FILE>;

# Joins all the array elements with "" (nothing), into one variable.
$text = join("", @text);

# s/string_to_search_for/string_to_replace_it_with/
# The "(\s+)" between "some" and "text"
# matches one or more whitespace characters.
# If a match is found in "()"
# the value of the match is stored in "$1".
# This value can then be put back in between the
# the two words you are replacing with.
$text =~ s/some(\s+)text/replace$1string/gi;

# print to the new file, close both files, goodbye!
print NEWFILE "$text";
close FILE;
close NEWFILE;
exit;


Regards,
Scott Prince

***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch