簡體   English   中英

sed用反斜杠替換嗎?

[英]sed substitution with backslash in pattern?

最好的問題描述是通過查看http://rubular.com/r/9zDHFh0gGc給出的。 為什么sed不能那樣工作? 我認為問題取決於片段中的反斜杠\\ ,例如{1+\\cos^2 t + t^2}中的反斜杠。
確切地說,我想替代源代碼

Test Text
= \int_0^{\pi}\vvvec
{1+\cos^2 t + t^2}
{1+ \sin^2 t + t^2}
{1 + 2 t^2}
\cdot \vvvec{-2\cos t \sin t}{2\cos t \sin t}{2t}\ud t =
Ende

通過命令sed -r 's/\\\\vvvec[[:space:]]*\\{([^\\}]*)\\}[[:space:]]*\\{([^\\}]*)\\}[[:space:]]*\\{([^\\}]*)\\}/\\\\begin\\{pmatrix\\}\\1\\\\\\\\\\2\\\\\\\\\\3\\\\end\\{pmatrix\\}/g' source ,希望能得到結果

Test Text
= \int_0^{\pi}\begin{pmatrix}1+\cos^2 t + t^2\\1+ \sin^2 t + t^2\\1 + 2 t^2\end{pmatrix}
\cdot \begin{pmatrix}-2\cos t \sin t\\2\cos t \sin t\\2t\end{pmatrix}\ud t =
Ende

對不起-我看不到,為什么不起作用。
該字符串似乎還可以,例如echo "\\vvvec{1}{2}{3}" | sed -r 's/\\\\vvvec[[:space:]]*\\{([^\\}]*)\\}[[:space:]]*\\{([^\\}]*)\\}[[:space:]]*\\{([^\\}]*)\\}/\\\\begin\\{pmatrix\\}\\1\\\\\\\\\\2\\\\\\\\\\3\\\\end\\{pmatrix\\}/g' \\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix} echo "\\vvvec{1}{2}{3}" | sed -r 's/\\\\vvvec[[:space:]]*\\{([^\\}]*)\\}[[:space:]]*\\{([^\\}]*)\\}[[:space:]]*\\{([^\\}]*)\\}/\\\\begin\\{pmatrix\\}\\1\\\\\\\\\\2\\\\\\\\\\3\\\\end\\{pmatrix\\}/g' \\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}工作正常。 例如,在一個組件中插入\\sin時,它將停止工作。

字符類中不需要反斜杠,實際上,它會將反斜杠添加到類中。 因此\\{([^\\}]*)\\}{\\cos t}不匹配。

因此,這似乎可行:

sed -r 's/\\vvvec[[:space:]]*\{([^}]*)\}[[:space:]]*\{([^}]*)\}[[:space:]]*\{([^}]*)\}/\\begin\{pmatrix\}\1\\\\\2\\\\\3\\end\{pmatrix\}/g'

要正確處理反斜杠,您可以:

  • \\轉換為@

     $ tr '\\\\' '@' <input.txt 
  • 運行sed命令(也可以使用@作為\\

     $ sed ... >output.txt 
  • @翻譯回\\

     $ tr '\\\\' '@' <output.txt 
  • 最后,用管道輸送所有這些命令

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM