In three steps, using sed syntax compatible with /usr/bin/sed on macOS, and either bash or zsh (the two main shells on current macOS systems):
sed -n '/hello/=' sample.txt |
sed -e '$!d' -e $'s/.*/&r sample1.txt\\\n&d/' |
sed -f /dev/stdin sample.txt
This uses sed in three steps:
Finds all lines in sample.txt that matches hello and output the line numbers corresponding to those lines.
Deletes all but the last line number outputted by the first step (using $!d, "if this is not the last line, delete it"), and creates a two-line sed script that would modify the last matching line by first reading sample1.txt and then deleting the original line. Given that the last match of hello is on line 3 in the original file, this script would look like
3r sample1.txt
3d
Applies the constructed sed script on the file sample.txt.
Would you want to make the edit "in-place", so that the original sample.txt is modified, then use
sed -n '/hello/=' sample.txt |
sed -e '$!d' -e $'s/.*/&r sample1.txt\\\n&d/' |
sed -i '' -f /dev/stdin sample.txt
The same set of commands, but using your variables $sample_file_path and $sample_file_path_1 for the two file paths:
sed -n '/hello/=' "$sample_file_path" |
sed -e '$!d' -e 's,.*,&r '"$sample_file_path_1"$'\\\n&d,' |
sed -i '' -f /dev/stdin "$sample_file_path"
Note that I have changed the delimiters in the second command from / to , as the file path contains slashes. You may use any character as a delimiter in the s/// command that is not otherwise part of the regular expression or replacement text.
othellofor example and should that count as a match ofhello? Does it absolutely need to besedor are you open to tools likeawkorperl?