Question

I have a quick question..

I am trying to match a specific mulitline instance. The problem is that when I execute my code, it only prints what I have edited and not the entire file with it.

For example. This is my input:

JJJ
1234          123.00     1234.28               123456.00     1234567.72 constant
ld;afksd;l REst of file blah blah blah...rest of file and other info I neeed etc.

My goal is to get:

JJJ 1234          123.00     1234.28               123456.00     1234567.72 constant
ld;afksd;l REst of file blah blah blah...rest of file and other info I neeed etc.

So basically I am just trying to slurp the data up to the line with JJJ or any other variation of 1 or more capital letters.

When I do it however, I only get this:

JJJ 1234          123.00     1234.28               123456.00     1234567.72 constant

I only get that and only that and not the other info i need in the file. I know there is a simple solution but I am very new to perl and can't quite figure it out.

Here is my code, maybe some of you will have suggestions.

use File::Slurp;
my $text = read_file( 'posf.txt' );
while ($text =~ /(^[A-Z]+)(\d+.*?\.\d+ Acquired$)/gism) {
$captured = $1." ".$2;
$captured =~ s/\n//gi;

print $captured."\n";
}

Any help would be great. I know I am just telling the program to print "captured" but I can't figure out how to get it to print the rest of the file and slurp the line up to the desired position.

I hope my question makes sense and is not hard to understand, let me know if I can further inquire.

Was it helpful?

Solution

Hopefully, I understood your problem correctly: you want to remove the newline after every line in the text, containing only capital letters. Try this code:

#!/usr/bin/perl

use strict;
use warnings;

my $text = qq{JJJ
1234          123.00     1234.28               123456.00     1234567.72 constant
ld;afksd;l REst of file blah blah blah...rest of file and other info I neeed etc.
JJJ
1234          123.00     1234.28               123456.00     1234567.72 constant
ld;afksd;l REst of file blah blah blah...rest of file and other info I neeed etc.
};

$text =~ s/(^[A-Z]+) #if the line starts with at least 1 capital letter
      \r?            #followed by optional \r - for DOS files
      \n$/           #followed by \n
      $1 /mg;        #replace it with the 1-st group and a space
print $text;

It prints:

JJJ 1234          123.00     1234.28               123456.00     1234567.72 constant
ld;afksd;l REst of file blah blah blah...rest of file and other info I neeed etc.
JJJ 1234          123.00     1234.28               123456.00     1234567.72 constant
ld;afksd;l REst of file blah blah blah...rest of file and other info I neeed etc.

I didn't read the text from file to show the test data. But you can easily add read_file call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top