Mark.Allan has asked for the wisdom of the Perl Monks concerning the following question:
Monks
Not sure how this can be so hard but here goes, im trying to search for files in a directory which match a certain pattern, this is easy, when I find these files I want to read through them, search for a string which matches a specific pattern then edit these files by adding an # at the start of the matched line.
Can I do this with one search and replace by appending the current file and editing. I thought this would be simple, it probably is for you gurus but I'm only an "occasional" scripter
Here is what I got so far. I could have multiple files called rc.itm1 or rc.itm2 etc in the /etc dir. So I need to find these files, edit a line which matches "start ux" by inserting an # at the beginning of line
Current code finds the files, finds the string, and prints the string with an # in front but I'm struggling to work out how to successfully search and replace this string in the same file and save it off.
current code....
Can anyone help me out please?#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $dir="/etc"; opendir ( DIR, $dir ) || die "Error in opening dir $dir\n"; my @files=sort(grep(/^rc\.itm\d+$/, readdir(DIR))); closedir(DIR); foreach my $file(@files){ my $this_file=$dir . "/" . $file; print "$this_file\n"; open IN, "< $this_file"; while (<IN>){ if ($_ =~ /start ux/){ print "#$_"; } } }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Write to existing file with character insert
by Don Coyote (Hermit) on Oct 24, 2012 at 12:39 UTC | |
by Anonymous Monk on Oct 24, 2012 at 12:43 UTC | |
Re: Write to existing file with character insert
by Anonymous Monk on Oct 24, 2012 at 12:37 UTC | |
Re: Write to existing file with character insert
by zwon (Abbot) on Oct 24, 2012 at 16:16 UTC | |
by Anonymous Monk on Oct 24, 2012 at 19:08 UTC | |
Re: Write to existing file with character insert
by Kenosis (Priest) on Oct 24, 2012 at 19:19 UTC | |
by Anonymous Monk on Oct 25, 2012 at 02:24 UTC |