Find the answer to your Linux question:
Results 1 to 3 of 3
Hello All, I'm trying to replace some specific text in like 600 files in a directory. I've been working with sed but i'm open to anything that works. Basically I ...
  1. #1
    Just Joined!
    Join Date
    Nov 2008
    Posts
    2

    Regular expression hell

    Hello All,
    I'm trying to replace some specific text in like 600 files in a directory. I've been working with sed but i'm open to anything that works. Basically I want to replace a period or periods that occur between to other certain characters on every line in the file. For example this line:

    [5.6h>VistaRelease5.6h] | blah blah
    [6.0.1>VistaRelease6.0.1] | blah blah .

    So I want to replace only the periods that are between the ">" and the "]" with an underscore. I have been able to replace the ">" to the "]" with an underscore producing [6.0.1_ | blah blah. But obviously this is not what i'm looking for. I used ..sed 's/>.*[]]/_/'

    Any help would be appreciated.

  2. #2
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    I don't think this can be done with a regular expression. Try this Perl script as a filter:
    Code:
    #!/usr/bin/perl
    
    while($in_line=<STDIN>)
    {
      chomp($in_line);
    
      # Don't change any lines which do not contain > followed somewhere by ].
    
      if($in_line!~/\>.*\]/)
      {
        print("$in_line\n");
    
        next;
      }
    
      $first_part=$in_line;
    
      $first_part=~s/^([^>]*)(.*)$/$1/;
      $in_line   =~s/^([^>]*)(.*)$/$2/;
    
      $second_part=$in_line;
    
      $second_part=~s/^([^\]]*)(.*)$/$1/;
      $in_line    =~s/^([^\]]*)(.*)$/$2/;
    
      $second_part=~s/\./\_/g;
    
      print("$first_part$second_part$in_line\n");
    }
    I've briefly tested it, and it seems to work.

    If you prefer awk to Perl, there's a good chance that an awk expert will be along to give an awk alternative.

    And, of course, there's also a good chance that someone will come along with a regular expression that does the job handily.

    But in the meantime, this script will work.

    Depending on your distribution, you may have to change its first line, though:
    Code:
    #!/usr/bin/perl
    to reflect the location of Perl on your system. To find that, do this at the command line:
    Code:
    which perl
    Hope this helps.
    --
    Bill

    Old age and treachery will overcome youth and skill.

  3. #3
    Just Joined!
    Join Date
    Nov 2008
    Posts
    2
    Thank you. It works perfectly. I made a little bash script to iterate all 600 files applying your perl filter and it works great. Thank you very much.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...