0

I am looking to add effects used in Github Markdown syntax into the command line. Take, for example, this string.

`This` is an `example` of Markdown `code snippets.`

I want to change every first backtick to—let's say—FOO but change every other backtick to BAR. How can I do with this in sed?

  • I might be misunderstanding your intention. Do you intend to replace all even-numbered occurences of ` with one pattern and odd-numbered by another? In this case, sed 's:`\([^`]*\)`:FOO\1BAR:g' would work (see https://unix.stackexchange.com/questions/77831/replace-every-odd-or-even-occurrence-of-a-pattern-in-a-file). If you want to replace the first ` with one pattern and the remaining with another, two sed invocations should do: sed 's:`:FOO:' | sed 's:`:BAR:g' –  Apr 20 '18 at 23:19
  • have you tried something already ? – el-teedee Apr 20 '18 at 23:20
  • The comment system seems to mangle the backtick character... so assume "#" for backtick. Then the sed invocations in my previous comment would be sed 's|#\([^#]*\)#|FOO\1BAR|g' and sed 's|#|FOO|' | sed 's|#|BAR|g', respectively. –  Apr 20 '18 at 23:27
  • @Michael Oh. Well... thanks. Will try this one out later. – PistolRcks Apr 21 '18 at 04:46
  • @MichaelEngel Tried this one out, and it works. Thank you. Could you please write your answer so that I can mark it correct? EDIT: You forgot backslashes before the beginning parenthesis and closing parenthesis in your second comment. – PistolRcks Apr 21 '18 at 04:55
  • @PistolRcks Done - and thanks for noticing the backslashes were missing. –  Apr 21 '18 at 08:52

1 Answers1

0

There are two possible scenarios that seem to be of interest here:

Replace all even-numbered occurences of ` with one pattern and odd-numbered by another (also mentioned in this answer):

sed 's:`\([^`]`*\)`:FOO\1BAR:g'

Replace the first with one pattern and the remaining with another:

sed 's:`:FOO:' | sed 's:`:BAR:g'