0

I'm trying to dynamically generate table of content for my markdown files, and trying to add it into the start of my markdown files.

But the dynamically generated TOC may contains some single quote or double quote, which leads the fail of sed execution.

Is there a way that I can add these dynamically generated TOC to the beginning of file using sed? How?

Below is my script and the error info:

# filename: add_toc.sh
TOC=$(./gh-md-toc $1)
sed -i "1s/^/"$TOC"/" $1


# Execution 
./add_toc.sh my_doc.md
sed: -e expression #1, char 5: unterminated `s' command
  • Can you show a sample value of TOC that fails for you? – Inian Mar 13 at 8:29
  • Why not avoid the issue altogether by doing something like { ./gh-md-toc "$1" ; cat "$1"; } > tmpfile and then mv tmpfile "$1"? – steeldriver Mar 13 at 8:32
  • @steeldriver, that's what I did after ask this question, but I'm still curious about if sed can do what I want to do in this question. – Zen Mar 13 at 9:10
  • You're likely better off using ed - where you could use the ! form of r to read the output of the TOC generator command into the file as text, with no possibility of it being interpreted – steeldriver Mar 13 at 9:23
0

I'd suggest using ed rather than sed, with the ! form of its r command to read the output of the TOC generator command into the file as text, with no possibility of it being interpreted.

Ex. (untested - since I don't have the ./gh-md-toc script):

ed -s "$1" <<EOF
0r !./gh-md-toc "$1"
wq
EOF

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.