我想使用shell(bash)将<tr>
的第一个实例替换为<tr class="active">
。
然而,这个sed没有任何影响:
sed '0,/<tr>/s/<tr>/<tr class="active">/' FILE1 >> temp2.txt
temp2.txt仍然是
<tr>
<th>set</th>
<th>Run</th>
<th>Continuum<br>filter</th>
<th>Narrow Band<br>filter</th>
</tr>
<tr>
<td><a href="#set1">1</a></td>
<td>Run09</td>
<td>R_Harris</td>
<td>6605/32</td>
</tr>
此代码同时更改<tr>
sed '1,/<tr>/s/<tr>/<tr class="active">/' FILE1 >> temp2.txt
有人可以解释发生了什么吗?
<tr class="active">
<th>set</th>
<th>Run</th>
<th>Continuum<br>filter</th>
<th>Narrow Band<br>filter</th>
</tr>
<tr class="active">
<td><a href="#set1">1</a></td>
<td>Run09</td>
<td>R_Harris</td>
<td>6605/32</td>
</tr>
答案 0 :(得分:2)
尝试以下命令。
sed -e '1,/<tr>/ s/<tr>/<tr class="active">/'
此命令将替换&lt; tr>与&lt; tr class =“active”&gt;
从第1行到第一行&lt; tr>找到。
答案 1 :(得分:0)
尝试以下sed命令,
$ sed '0,/<tr>/{s/<tr>/<tr class=\"active\">/}' file
<tr class="active">
<th>set</th>
<th>Run</th>
<th>Continuum<br>filter</th>
<th>Narrow Band<br>filter</th>
</tr>
<tr>
<td><a href="#set1">1</a></td>
<td>Run09</td>
<td>R_Harris</td>
<td>6605/32</td>
</tr>
答案 2 :(得分:0)
这应该这样做:
sed '0,/\<tr\>/s/tr/tr class=\"active\"/' FILE1 >> temp2.txt
或者您可以使用以下方式编辑FILE1:
sed -i '0,/\<tr\>/s/tr/tr class=\"active\"/' FILE1
输出:
alchemy:~/scr/tmp/stack/dat> sed '0,/\<tr\>/s/tr/tr class=\"active\"/' table.html
<tr class="active">
<th>set</th>
<th>Run</th>
<th>Continuum<br>filter</th>
<th>Narrow Band<br>filter</th>
</tr>
<tr>
<td><a href="#set1">1</a></td>
<td>Run09</td>
<td>R_Harris</td>
<td>6605/32</td>
</tr>
关于你的无效命令,`0,/ regex / s / this / to_that /&#39;与&#39; 1,/ regex ...&#39;
相比,语法将执行以下操作0,addr2
Start out in "matched first address" state, until addr2 is found. This
is similar to 1,addr2, except that if addr2 matches the very first line of
input the 0,addr2 form will be at the end of its range, whereas the 1,addr2
form will still be at the beginning of its range. This works only when addr2
is a regular expression.
将输入复制到table2.html并使用sed -i
表单会产生以下结果:
$ sed -i '0,/\<tr\>/s/tr/tr class=\"active\"/' table2.html
$ cat table2.html
<tr class="active">
<th>set</th>
<th>Run</th>
<th>Continuum<br>filter</th>
<th>Narrow Band<br>filter</th>
</tr>
<tr>
<td><a href="#set1">1</a></td>
<td>Run09</td>
<td>R_Harris</td>
<td>6605/32</td>
</tr>
答案 3 :(得分:0)
这可能适合你(GNU sed):
sed '/<tr>/{s//<tr class="active">/;:a;n;ba}' file
替换第一次出现,然后对文件的其余部分不执行任何操作。
或者:
sed ':a;$!{N;ba};s/<tr>/<tr class="active">/' file
在整个文件中使用Slurp并替换第一次出现。