キャプチャグループ内の文字を置き換えるsed(またはその他の)スクリプト

キャプチャグループ内の文字を置き換えるsed(またはその他の)スクリプト

私はPandocマークアップをConfluence wikiマークアップに変換しようとしています。マークダウン2コンフルエンス作業の大部分を実行します。これは、コード内で{&を使用する 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 {{*}}.

{{${type.name}}}どちらになるべきかについても処理する必要があります{{$\{type.name\}}}

問題は2つある

  1. 引用符を使用する代わり{に に置き換える必要があるため、何らかの方法で変更する必要があります。\{\1
  2. 見た目が悪い{{}}}(出てくるはず)は、{{\}}}パターン マッチをどのように終了しようとしても正しく出力されません。

答え1

次の sed コマンドが機能するようです:

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

説明:

  1. {{\([^*[a-z][^}]*\)}}は、またはまたは小文字で始まる{{stuff}}場合を除き、を検索します。stuff*[
  2. に置き換えてください{{\stuff}}
  3. 次に を{{\\${\([^}]*\)}}}見つけます{{\${junk}}}
  4. そしてそれを に置き換えます{{$\{junk\}}}

編集: OP からの説明の後、代替の解決策は次のようになります。

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

ご存知のとおり、sed は再帰解析を実行できませんが、ほとんどの単純なケースでは機能するはずです。

説明:

  1. \({{[^}]*\){\([^}]*}}\){{foo{bar}}は、fooと をbar含まない を検索します}
  2. そしてそれを に置き換えます{{foo\{bar}}。(メモは{{xxx{yyy}}}正常に処理されます。)
  3. 次に、 を含まない を\({{[^}]*\)}}}検索します。{{baz}}}baz}
  4. そしてそれを に置き換えます{{baz\}}}

foobar、 はbaz空になる可能性があるため、たとえば は必要に応じて{{}}}に変換されます{{\}}}

関連情報