wcj75019 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Brothers and Sisters. I am trying to write a script to change change 100's of files. Change a line if it exists or add it if it doesn't exist. I'm having multiple issues. I thought I would grep to see which files don't have the line. Then from that array add the line. all the rest just switch the line. I'm having problems with grep I'm reading in a list of files. I want to grep which files have the line with bgs in it. Replace that line with the new line which is the new way to start Best1. Many of the files don't have the line. So, for the files that don't have it. I need to add it. Then, I am going to open another file and do some more stuff to that. So, some of this code may not make sense. THANK You!
#!/usr/bin/perl -w use strict; open CF_FILES, "cf.files" or die "Error: $!"; my @cf_files=<CF_FILES>; close CF_FILES; foreach my $cf(@cf_files){ open CF, $cf my @AR =<CF>; my @L = grep( /bgs/, @AR); print @L; } ;
Thanks

Replies are listed 'Best First'.
Re: grep question
by runrig (Abbot) on Feb 20, 2008 at 23:24 UTC

    First, alway test the return of your open, e.g.:

    open F, $cf or die "Error: $!";

    Second, the string "bgs" is always true, so @CF_L will get the entire @F_cf array...maybe you wanted /bgs/? see perlre (and grep).

    Third, perl grep is not the same as Unix command line grep. But I probably would use command line grep for this.

    Fourth, please wrap your code in <code>...< /code> tags. It's easier to read that way.

Re: grep question
by CountZero (Bishop) on Feb 21, 2008 at 07:06 UTC
    I'm having problems with grep
    And what kind of "problems" that might be?

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      I'm reading in a list of files. I want to grep which files have the line with bgs in it. Replace that line with the new line which is the new way to start Best1. Many of them don't have the line. So, for the files that don't have it. I need to add it.