[CentOS] text processing problem with bash/perl

Fri Feb 13 10:50:41 UTC 2009
Dave Cross <davorg at gmail.com>

2009/2/13 Robinson Tiemuqinke <hahaha_30k at yahoo.com>:
> Hi,
>
> Anyone has some ways for the following text processing problem? I have a text file
> containing two stanzas attached below. I want to uncomment the stanza with
> 'host=localhost' line, while left the other stanza unchanged.
>
> ...
>
> /* udp_send_channel {
>  host=localhost
>  port = 10017
>  ttl = 1
> } */
>
> /* udp_send_channel {
>  host=ganglia100.ec2.example.com
>  port = 10017
>  ttl = 1
> } */

It's pretty simple in Perl. Something like this will work.

#!/usr/bin/perl
use strict;
use warnings;

# Put Perl in "paragraph mode"
$/ = '';

# For each record ...
while (<>) {
  # ... if the record is for localhost ...
  if (/host=localhost/) {
    # ... remove the opening comment ...
    s|/\*\s*||;
    # ... remove the closing comment ...
    s|\s*\*/||;
  }

  # ... and print the record.
  print;
}

It's written as a Unix filter, so it reads from STDIN and writes to
STDOUT. Call it like this:

  $ my_filter < input.txt > output.txt


hth,

Dave...