paperazzo79
paperazzo79

Reputation: 357

Perl: insert elements of array in file by substitution

1) I have a textfile. The file contains a STRING that needs to be substituted with multiple lines, those lines are elements of an array.

Contents of file:

line 1  
line 2   
line 3  
STRING  
line 4  
...  

2.)I have an array

@array = qw (ele1 ele2 ele3);

This array can have 2 or more elements.

3.)I want to open the file, substitute the STRING with following pseudocode:

s/STRING/@array/;  

and write results in a new file.

4.) The new file with result should look like this :

line 1  
line 2   
line 3  
ele1  
ele2  
ele3
line 4  
...

Here a piece of pseudocode:

open (FILE "< file.txt");
open (OUTPUT "> new.txt");
@array=qw(ele1 ele2 ele3);
for $line (<FILE>) {
    s/STRING/@array/;
    print OUTPUT "$line\n";
}
close FILE;
close OUTPUT;

Any suggestions on how to insert elements of an array into this file using substitution?

I am not looking for solutions based on sed, awk, cat or Unix shell tools.

Upvotes: 0

Views: 506

Answers (3)

Saravanan
Saravanan

Reputation: 119

You can also use onliner

perl -pi -e '@a=qw(a b c d e);$aa=join("\n",@a);s/string/$aa/g;' tt.txt

Upvotes: 0

Rich Daley
Rich Daley

Reputation: 1

You can actually do this without the /e operator, using the $" variable ($LIST_SEPARATOR if you use English), which changes how arrays are joined when interpolated into strings (including the right-hand side of a s///):

$" = "\n";
@array = qw(ele1 ele2 ele3);
open FILE, 'file.txt';
open OUTPUT, '>', 'new.txt';
while (<FILE>) {
  s/^STRING$/@array/;
  print OUTPUT;
}

Note also that you need ^ and $ anchors on your regexp if you don't want it to match lines containing the word "STRING".

Upvotes: 0

Toto
Toto

Reputation: 91518

You could do:

my $str = "line 1
line 2
line 3
STRING
line 4";
my @array = qw (ele1 ele2 ele3);
$str =~ s/STRING/join"\n",@array/e;
say $str;

Output:

line 1
line 2
line 3
ele1
ele2
ele3
line 4

Upvotes: 1

Related Questions