Skip to main content
edited tags
Link
Jeff Schaller
  • 68.8k
  • 35
  • 122
  • 264
Source Link

Replace fenced block with output of command in bash

I'm attempting to replace a "fenced" block of text with the output from the tree command in linux (specifically in a make file). Here's my input file:

some text...
[fencetitle]
----
.
├── file1.txt
└── test
    └── file2.txt

1 directory, 2 files
----
some more text...

And I'd like to replace the contents with output from the tree command:

some text...
[fencetitle]
----
.
├── file1.txt
├── newfile.txt
└── test
    └── file2.txt

1 directory, 3 files
----
some more text...

Using the sed command, I can't seem to match using newlines with the line [fencedtitle] and ---- to ----. I am able to replace text between [fencedtitle] and ---- with the following command, however:

sed -n '/\[fencedtitle\]/{:a;N;/----/!ba;N;s/.*\n/REPLACEMENT\n/};p' file

But I can't seem to then replace REPLACEMENT with the output from the tree command. Is sed the right approach here, or is something else more appropriate?