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....

#!/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 "#$_"; } } }
Can anyone help me out please?

In reply to Write to existing file with character insert by Mark.Allan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.