I am writing a script to append text file by adding some text under specific string in the file after tab spacing. Help needed to add new line and tab spacing after matched string "apple" in below case.
Example File:
apple
<tab_spacing>original text1
orange
<tab_spacing>original text2
Expected output:
apple
<tab_spacing>testing
<tab_spacing>original text1
orange
<tab_spacing>original text2
What i have tried:
use strict;
use warnings;
my $config="filename.txt";
open (CONFIG,"+<$config") or die "Fail to open config file $config\n";
while (<CONFIG>) {
chop;
if (($_ =~ /^$apple$/)){
print CONFIG "\n";
print CONFIG "testing\n";
}
}
close CONFIG;
Some pretty weird stuff in your code, to be honest:
CONFIG
) instead of a lexical variable and two-arg open()
instead of the three-arg version (open my $config_fh, '+<', $config'
) makes me think you're using some pretty old Perl tutorialschop()
instead of chomp()
makes me think you're using some ancient Perl tutorials$
in your regex - ^$apple$
should probably be ^apple$
Also, Tie::File has been included with Perl's standard library for over twenty years and would make this task far easier.
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File;
tie my @file, 'Tie::File', 'filename.txt' or die $!;
for (0 .. $#file) {
if ($file[$_] eq 'apple') {
splice @file, $_ + 1, 0, "\ttesting\n";
}
}