1

I have two bash arrays, one containing filenames and the other containing line numbers:

filepaths=(fig/par1.tex fig/par2.tex fig/par3.tex)

lines=(5 10 15)

I have another file (file.tex) into which I want to insert the contents of each file listed in $filepaths at the corresponding line number in $lines$, replacing the content of that line in file.tex. For example the contents of fig/par1.tex would replace line 5 of file.tex and the contents of fig/par2.tex would replace line 10 of file.tex.

I tried using a for loop, iterating over the array index:

for ((i=0;i<${#filepaths[@]};++i)); do
    sed -i "${lines[i]}r ${filepaths[i]}" file.tex
done

But I get an error for each iteration of the loop:

sed: 1: "file.tex": invalid command code f

The suggested question Bash tool to get nth line from a file provides an answer to print a particular line in a file by line number. This does not answer my question, which relates to iterating over array variables to insert text at a line number.

John L. Godlee
  • 559
  • 5
  • 21

1 Answers1

1

You may use this script:

s=

# loop through array and build sed command
for ((i=0;i<${#lines[@]};++i)); do
   printf -v s '%s%s\n%s\n' "$s" "${lines[i]}r ${filepaths[i]}" "${lines[i]}d"
done

# check sed command    
# echo "$s"

# run a single sed
sed -i.bak "$s" file.tex

It is important to use an alternate delimited in sed i.e. ~ since your replacement string has / in it.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • This answer inserts the _filepath_ of each file in `$filepaths` whereas I want the _contents_ of each file in `$filepaths`. – John L. Godlee Apr 02 '20 at 11:15