
我想這會是一件相當困難的事。
我必須擺弄內聯文檔,這些文檔被提取到 html 文件中以用作在線文檔,但文件的這些部分
在內聯形式中應該沒有 html 標籤,而僅在提取的 html 文件上。然而,由於這些文件部分也被提取到 .wiki 文件中,因此一些標籤已經存在,如下所示。
this is some text describing what is done
<code>
here are
some line that will be shown as code in wiki
but not on html cause they are shown on one line
in html output
</code>
some more describing text
<code>
another piece of code
that shows up as multiple lines in the wiki
but not in htmls
</code>
透過 sed 輕鬆完成文件的這些部分的提取後,我想將提取的文件 sed 到此:
this is some text describing what is done
<code><br/>
here are <br/>
some line that will be shown as code in wiki <br/>
but not on html cause they are shown on one line<br/>
in html output<br/>
</code><br/>
some more describing text
<code><br/>
another piece of code <br/>
that shows up as multiple lines in the wiki<br/>
but not in htmls<br/>
</code><br/>
到目前為止我得到的是這條 sed 行:
sed -i '/\<code>/,/\<\/code>/{s/$/\<br\/>/}' file
但它也會將 html 標籤附加到程式碼區域之間的文本,如下所示:
this is some text describing what is done
<code><br/>
here are <br/>
some line that will be shown as code in wiki <br/>
but not on html cause they are shown on one line<br/>
in html output<br/>
</code><br/>
<br/>
some more describing text<br/>
<code><br/>
another piece of code <br/>
that shows up as multiple lines in the wiki<br/>
but not in htmls<br/>
</code><br/>
這基本上是正確的,因為 sed 附加到第一個and the last
標記之間的所有行,但這不是我想要的。
有人可以給我一個提示,告訴我我在這裡缺少什麼嗎?
答案1
您的反斜線不正確。該表達式\<
確實不是匹配文字左斷言 - 未轉義的<
匹配本身很好,但是使用反斜杠,您可以將其更改為左字邊界零寬度斷言,這永遠不會發生在斜杠旁邊;所以這個表達式\</code>
永遠不能匹配任何東西。
透過一些小的重構來修復其他純粹多餘的超正確性,固定sed
腳本是
sed -i '/<code>/,\%</code>%s:$:<br/>:' file
我冒昧地將斜線更改為其他內容,以進一步消除對反斜線的需求。
答案2
好吧,找到了解決方法,雖然不是用sed
,而是用awk
。
awk '
BEGIN{c=0} // initialize variable with zero
/\<code>/{c=1} // if start pattern found set variable to 1
{if (c==1) print $0,"<br/>"} // if variable is one, append tag
{if (c==0) print $0} // if variable is zero just print line
/\<\/code>/{c=0} //if endpattern is found set variable to zero
'
這實際上非常簡單但優雅。