Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse and rearrange hostnames

Tags:

c++

python

awk

perl

Below is a list of hostnames that is stored in a text file.

web1.maxi.com
web3.maxi.com
web4.maxi.com
web5.maxi.com
web6.maxi.com
web7.maxi.com
web8.maxi.com
web9.maxi.com
web11.maxi.com

for the sake of displaying it shortly it needs to be parsed and rewritten/displayed as

web[1,3-9,11].maxi.com

can you guys help me on this, any suggestions will be helpful.

like image 334
Kannan Mohan Avatar asked Sep 19 '12 03:09

Kannan Mohan


1 Answers

With perl you can use the Set::IntSpan module for compressing the number sequence.

The below solution can handle mixed and unordered site listings.

infile

web3.maxi.com
web4.maxi.com
web5.maxi.com
mail1.mexi.com
web6.maxi.com
web9.maxi.com
web9.maxi.com

web11.maxi.com
mail3.mexi.com
web7.maxi.com
mail4.mexi.com
mail25.mexi.com      
  mail26.mexi.com
mail27.mexi.com
mail28.mexi.com
  web8.maxi.com
mail29.mexi.com
mail110.mexi.com
web1.maxi.com

parse.pl

#!/usr/bin/perl -l

use Set::IntSpan;
use File::Slurp qw/slurp/;

$str = slurp(\*STDIN);

# Remove redundant whitespace
chop $str;
$str =~ s/^[\t ]+|[\t ]+$//gm;
$str =~ s/\R+/\n/g;

# Copy $str so we can match numbers in it without disturbing the loop
$nums = $str;

# Parse lines in $str in sequence
while($str =~ /^(.*)$/gm) {
  $line = $1;

  # Extract bits before and after number
  ($pre, $post) = $line =~ /([^\d]+)\d+(.*)$/m;

  # Check if its been printed already
  next if $seen{$pre . $post};

  # If not, extract numbers
  @numbers = $nums =~ /$pre(\d+)$post/g;

  print $pre . "[" 
        . Set::IntSpan->new(@numbers)->run_list()
        . "]" . $post;

  $seen{$pre . $post} = 1;
}

Run it like this:

perl parse.pl < infile

Output:

web[1,3-9,11].maxi.com
mail[1,3-4,25-29,110].mexi.com

The perhaps cryptic @numbers = $nums =~ /$pre(\d+)$post/g expands to an array of items matched by the regular expression and saves it in @numbers.

Note that this solution loads the whole file into memory.

like image 78
Thor Avatar answered Nov 07 '22 08:11

Thor