Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

perl - Replacing some string in a text file shifts the remaining text to next line

I am trying to replace a string in a text file using Perl script. The value gets replaced successfully. However, it shifts the remaining text of the line to the next line. I want the line to be intact as before. Can someone help?

sample_file_dml has the below text in it:

seq_no,1,1,GET,xyz
seq_no,1,2,PUT,xyz

I want to replace seq_no in each line with the value of variable seq_no_value. This value is obtained through some calculations in my code (for example - 9999).

Expected output:

9999,1,1,GET,xyz
9999,1,2,PUT,xyz

But, I am getting the below output:

9999
,1,1,GET,xyz
9999
,1,2,PUT,xyz

Code snippet used:

        open my $IN, '<', $sample_dml_file or die $!;
        open my $OUT, '>>', $new_dml_file or die $!;
        
        while (<$IN>) {
            s/(seq_no)/$seq_no_value/g;
            print {$OUT} $_;
        }
        close $OUT or die $!;
question from:https://stackoverflow.com/questions/65901232/replacing-some-string-in-a-text-file-shifts-the-remaining-text-to-next-line

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe $seq_no_value also has a newline character in it at the end ( ). You can remove it with chomp:

chomp $seq_no_value;

Perhaps you were reading lines of a file when you set the variable.

Here is a self-contained example:

use warnings;
use strict;

my $seq_no_value = "9999
";
chomp $seq_no_value;
while (<DATA>) {
    s/(seq_no)/$seq_no_value/g;
    print $_;
}

__DATA__
seq_no,1,1,GET,xyz
seq_no,1,2,PUT,xyz

This outputs:

9999,1,1,GET,xyz
9999,1,2,PUT,xyz

If you comment out the chomp line, you get your original results.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...