Finding and Replacing portions by start and end points (alongside returning interior numeral)

1

I have to work through some really old code which repeats itself really often. So in trying to clear it I've come across this problem due to the monumental scale of it all.

<A>
   hello! my inside contents can vary
   5
</A>

I don't think there is any reasonable way to do this, but I want to replace the entirety of A and leave behind

blah(x)

Where x is the first number found inside of A.

D.W.

Posted 2017-02-14T10:21:49.497

Reputation: 11

Answers

0

Following perl script should do.

#! /usr/bin/env perl
# ------------------------------------------------
# Author:    krishna
# Created:   Sat Sep 22 09:50:06 2018 IST
# USAGE:
#       process.pl
# Description:
# 
# 
# ------------------------------------------------
$num = undef;

# Process the first argument as file and read the lines into $_
while (<>) {
  # remove newline at the end
  chomp;

  # True for all lines between the tag A
  if (/<A>/ ... /<\/A>/) {
    # Only when num is not defined, Capture only first occurance of a number
    $num = $& if not defined $num and /\d+/;
  } else {
    # Print other lines as it is
    printf "$_\n";
  }

  # After processing the tag, print the number and set to undef to capture next occurance
  if (/<\/A>/) {
    printf "blah($num)\n";
    $num = undef;
  }
}

To run

0 > perl ./process.pl file
blah(5)

blaaaaaaaaaa

blah(50)

where file contents are

0 > cat file
<A>
   hello! my inside contents can vary
   5
   505
</A>

blaaaaaaaaaa

<A>
   hello! my inside contents can vary
   50
</A>

HTH

Krishna

Krishna

Posted 2017-02-14T10:21:49.497

Reputation: 124