Operating System - HP-UX
1752608 Members
4396 Online
108788 Solutions
New Discussion юеВ

How to find and replace multiple lines.

 
panchpan
Regular Advisor

How to find and replace multiple lines.

Hello.
I have a input file containing multiple sets of following text:
----------------
:59:/1234567890
LINE1
LINE2
LINE3
:50:/9856958654
LINE1
LINE2
----------------

Basically, Tag 59 and Tag50 can have any number of lines in the input and any number against it. I want to write a script so that tag50 and tag59 could be found and the strings could be replaced as below:

----------------
:59:/XXXXXXXXXX
ZZZZZZZZ
ZZZZZZZZ
ZZZZZZZZ
:50:/XXXXXXXXXX
ZZZZZZZZ
ZZZZZZZZ
----------------

Your help will be highly appreciated. Thank you.
2 REPLIES 2
Dennis Handly
Acclaimed Contributor

Re: How to find and replace multiple lines.

>Tag 59 and Tag50 can have any number of lines in the input and any number against it.

So if you see :50: or :59: you want to replace the string on that line and up to a line with :XX: with "X" then "Z"?

Perhaps something like this:
awk '
BEGIN {
str1 = "/XXXXXXXXXX"
str2 = "ZZZZZZZZ"
replace = 0
}
substr($0, 1, 4) == ":50:" ||
substr($0, 1, 4) == ":59:" {
replace = 1
print substr($0, 1, 4) str1
next
}
substr($0, 1, 1) == ":" { # new tag?
replace = 0
}
replace {
print str2
next
}
{
print $0 # copy line
}' file
James R. Ferguson
Acclaimed Contributor

Re: How to find and replace multiple lines.

Hi:

Here's a solution based on your requirements' definition:

# cat ./filter
#!/usr/bin/perl
use strict;
use warnings;
local $/ = undef;
my @pieces = split( /(?=:\d+:\/.+)/, <> );
for (@pieces) {
my @subpieces = split( /$/m, $_ );
if (/^(:(50|59):\/)/) {
print $1, "XXXXXXXXXX\n";
shift @subpieces;
print "ZZZZZZZZZ\n" for ( 1 .. @subpieces - 1 );
}
else {
print $_;
}
}
1;

...run as:

# ./filter file

Regards!

...JRF...