How to replace text using greedy approach in sed?

十年热恋 提交于 2019-12-11 02:33:37

问题


I am parsing one file which has some html tag and changing into latex tag.

cat text

  <Text>A &lt;strong&gt;ASDFF&lt;/strong&gt; is a &lt;em&gt;cerebrovafdfasfscular&lt;/em&gt; condifasdftion caufadfsed fasdfby tfdashe l
 ocfsdafalised &lt;span style="text-decoration: underline;"&gt;ballooning&lt;/span&gt; or difdaslation of an arfdatery in thdfe bfdasrai
 n. Smadfsall aasdneurysms may dadisplay fdasno ofadsbvious sdfasigns (&lt;span style="text-decoration: underline;"&gt;&lt;em&gt;&lt;str
 ong&gt;asymptomatic&lt;/strong&gt;&lt;/em&gt;&lt;/span&gt;) bfdasut lfdsaarger afdasneurysms maydas besda asfdsasociated widfth sdsfudd

  sed -e 's|&lt;strong&gt;\(.*\)&lt;/strong&gt;|\\textbf{\1}|g' test

cat out

 <Text>A \textbf{ASDFF&lt;/strong&gt; is a &lt;em&gt;cerebrovafdfasfscular&lt;/em&gt;    condifasdftion caufadfsed fasdfby tfdashe locfsda
    falised &lt;span style="text-decoration: underline;"&gt;ballooning&lt;/span&gt; or    difdaslation of an arfdatery in thdfe bfdasrain. Sma
      dfsall aasdneurysms may dadisplay fdasno ofadsbvious sdfasigns (&lt;span style="text-decoration: underline;"&gt;&lt;em&gt;&lt;strong&gt
      ;asymptomatic}&lt;/em&gt;&lt;/span&gt;) bfdasut lfdsaarger afdasneurysms maydas besda   asfdsasociated widfth sdsfudd

Expected outputs should be \textbf{ASDFF} while i observe \textbf{ASDFF .........}. How to get expected result?

Regards


回答1:


You may want to use perl regex instead.

perl -pe  's|&lt;strong&gt;(.*?)&lt;/strong&gt;|\\textbf{\1}|g'

Your problem is similar with non-greedy-regex-matching-in-sed. And next time you may want to simplify your case to point out the real problem. For example, don't just paste the raw html code, use this instead:

fooTEXT1barfooTEXT2bar

Update

If you just want the greedy approach, just ignore this.



来源:https://stackoverflow.com/questions/14373441/how-to-replace-text-using-greedy-approach-in-sed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!