Sed (или другой) скрипт для замены персонажа в группе захвата

1009
Ian Turton

Я пытаюсь преобразовать разметку Pandoc в разметку wiki Confluence, я использую markdown2confluence, чтобы выполнить большую часть работы. Это работает довольно хорошо, за исключением тех случаев, когда я говорю о CSS и FreeMarker, которые используют {& }в коде, а Confluence использует {{&, }}чтобы отметить начало / конец блока кода. Поэтому мне нужно соответствовать шаблону, заключенному в {{...}}.

Если бы я знал (больше) Ruby, я мог бы исправить это там, но я парень из Unix старой школы, поэтому я подумал о awk или sed.

Итак, я дошел до:

 sed 's/{{\([^}}]*\)}}/{{"\1"}}/g' tmp.wkd 

который занимает:

First we need a way to select a state (or group of states) CSS uses what is called a selector to choose which elements to apply to, we have been using one up until now without noticing, it is the {{*}} at the beginning of our CSS. This is a special selector that means select everything. So the rule that follows it (the bit between {{{}} and {{}}} apply to every polygon on the map. But CSS allows us to insert a filter instead by using {{[...]}} instead of {{*}}. 

и производит:

First we need a way to select a state (or group of states) CSS uses what is called a selector to choose which elements to apply to, we have been using one up until now without noticing, it is the {{"*"}} at the beginning of our CSS. This is a special selector that means select everything. So the rule that follows it (the bit between {{"{"}} and {{""}}} apply to every polygon on the map. But CSS allows us to insert a filter instead by using {{"[...]"}} instead of {{"*"}}. 

Но то, что мне нужно, это:

First we need a way to select a state (or group of states) CSS uses what is called a selector to choose which elements to apply to, we have been using one up until now without noticing, it is the {{*}} at the beginning of our CSS. This is a special selector that means select everything. So the rule that follows it (the bit between {{\{}} and {{\}}} apply to every polygon on the map. But CSS allows us to insert a filter instead by using {{[...]}} instead of {{*}}. 

Также необходимо справиться с тем, {{$}}что должно стать {{$\}}.

Есть две проблемы

  1. Мне нужно заменить {с \{вместо того, чтобы использовать кавычки, так что мне нужно изменить \1каким - то образом.
  2. Гадкий вид {{}}}(который должен быть получен {{\}}}, не выходит правильно, независимо от того, как я пытаюсь закончить образец соответствия).
0
Можете ли вы опубликовать желаемый результат из приведенного выше примера? chaos 8 лет назад 1
было бы немного менее уродливо, если бы вы использовали sed -r, тогда вы могли бы сказать (`` вместо `\ (` barlop 8 лет назад 0

1 ответ на вопрос

2
Joseph Quinsey

The following sed command seems to work:

 sed 's/{{\([^*[a-z][^}]*\)}}/{{\\\1}}/g;s/{{\\${\([^}]*\)}}}/{{$\\{\1\\}}}/g' 

Explanation:

  1. {{\([^*[a-z][^}]*\)}} finds {}, except when stuff begins with * or [ or a lower-case letter.
  2. Replace it with {{\stuff}}.
  3. Then {{\\${\([^}]*\)}}} finds {{\$}}.
  4. And replaces it with {{$\}}.

Edit: An alternative solution, after clarification from the OP, could be this:

 sed 's/\({{[^}]*\){\([^}]*}}\)/\1\\{\2/g;s/\({{[^}]*\)}}}/\1\\}}}/g' 

As we all know, sed cannot do recursive parsing, but this should work for most simple cases.

Explanation:

  1. \({{[^}]*\){\([^}]*}}\) finds {}, where foo and bar do not contain }.
  2. And replaces it with {}. (Note {}} is handled ok.)
  3. Then \({{[^}]*\)}}} finds {}}, where baz does not contain }.
  4. And replaces it with {}}.

foo, bar, and baz can be empty, so for example {{}}} is converted to {{\}}}, as required.

закрыть, но он преобразует {} в {{\ type}}, в то время как он должен оставаться {} Ian Turton 8 лет назад 0
@iant Я добавил `az`, чтобы` {} `оставался неизменным. Но каковы правила для `type`? Joseph Quinsey 8 лет назад 0
в основном все, что не является , должно быть неизменным между {{}} Ian Turton 8 лет назад 0
@iant Спасибо за дополнительную информацию. Возможно, я удалю этот ответ и отправлю лучший. Joseph Quinsey 8 лет назад 0
Вы пишете «Возможно, я удалю этот ответ и отправлю лучший». <--- Есть кнопка редактирования. barlop 8 лет назад 2

Похожие вопросы