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' – user271639 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. – user271639 Apr 20 '18 at 23:27
  • @Michael Oh. Well... thanks. Will try this one out later. – PistolRcks Apr 21 '18 at 4: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 4:55
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'
  • sed can run multiple commands (including substitutions) in one go. – don_crissti Apr 21 '18 at 12:15

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.