在 html 檔案中,我只需要替換第一次出現的:
<table id="any string" >
“任何字串”是“”中的任何內容。最后一個 > 字符之前有一個空格。
預期輸出:
<table id="new string">
我知道也許 ased -i可以做到,但我不知道如何匹配“任何字串”部分并且只匹配第一次出現。
uj5u.com熱心網友回復:
使用sed分組和反向參考,您可以排除引號內的文本以及末尾的空格。
$ sed -i.backup '0,/table id/s/\(table id="\).*\("\) /\1new string\2/' input_file
<table id="new string">
這將創建原始檔案的備份。
uj5u.com熱心網友回復:
假設您any string實際上表示任何字串,因為您不知道它是什么并且它可以是任何東西,您必須使用引號作為分隔符。您提到了sed,這是一個簡單的sed解決方案:
# GNU sed needs -r for extended regexp, macOS sed needs -E for this
# s means for substitute
# / slashes are delimiters surrounding the paaterns, /before/after/
# [^ ] means any character that is *not* a space
# means one or more of those characters
# followed by a space
# (. ) means one or more of any character, and remember what it is
# \1 use that first remembered pattern
sed -r 's/table id="[^ ] (. )"/table id="new \1"/' file.html
因此,它將匹配一個帶有雙引號 ID 的表,其中包含一個空格,并將 ID 中直到該空格為止的所有內容替換為“new”。
例子:
<table id="any string" > -> <table id="new string" >
<table id="compact striped" > -> <table id="new striped" >
<table id="data compact striped" > -> <table id="new compact striped" >
如果any string實際上意味著任何字串,不一定帶有空格(例如“foo”),并且new string意味著任何新字串(例如 bar),那么問題就簡單多了:
sed -r 's/table id=". "/table id="new"/' file.html
例子:
<table id="foo bar" > -> <table id="new" >
<table id="jabberwocky" > -> <table id="new" >
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359463.html
