Using Raku (formerly known as Perl_6)
~$ raku -e 'my @a = dir(test => "Matsuo_Bashō.txt").IO.lines.join("\n"); for lines[0..9] { put S/e/@a[]/ };' alphabet.txt
a
b
c
d
No one travels
Along this way but I,
This autumn evening.
f
g
h
i
j
Original_File being substituted == alphabet.txt
~$ raku -e 'for lines[0..9] { .put };' alphabet.txt
a
b
c
d
e
f
g
h
i
j
Second File to be inserted == Matsuo_Bashō.txt
~$ raku -e 'put dir(test => "Matsuo_Bashō.txt").IO.lines.join("\n");'
No one travels
Along this way but I,
This autumn evening.
Briefly, take the file you want to "insert" and read it in using Raku's dir()
routine, storing it in the @a
array. Then the second 'target' file (here an alphabetic sequence) is read-in off the command line. Raku will output the resultant string when substituted with the S///
"big-S" substitution operator. Note: the code above will only replace the first occurrence. To make this a global replacement (replacing all occurences of the recognition sequence e
, add the :global
adverb: S:global///
or more simply, S:g///
.
There's no need to backslash @a
in the replacement, simply add indexing square-brackets at the end: @a[]
(curlies work also, see below).
If you don't want to substitute but instead want to insert a second file after a recognition sequence in the first, change the substitution operator to use a lookbehind assertion, and add a newline before the replacement:
{ put S/ <?after e> /\n@a[]/ }
#OR
{ put S/ <?after e> /\n{@a}/ }
Finally note that files can be slurp
ed-in all at once. Using Raku's dir()
routine that's:
dir(test => "Matsuo_Bashō.txt").IO.slurp;
...however an extra newline gets added to the output. You can use slurp
and trim-trailing
to replicate the answer above (below, a shorthand way of quoting the dir()
filename string is to enclose it in angle brackets):
~$ raku -e 'my @a = dir(:test<Matsuo_Bashō.txt>).IO.slurp; for lines[0..9] { put S/e/{@a[].trim-trailing}/ };' alphabet.txt
https://raku.org