gpt4 book ai didi

linux - sed:在某个位置插入一行

转载 作者:太空宇宙 更新时间:2023-11-04 04:36:54 29 4
gpt4 key购买 nike

我只是环顾四周,但没有找到任何适合我的东西。我想在其他行的顶部插入一个新行(基本上是一个 html 表格行)。

<table id="tfhover" class="tftable" border="1">
<tr><th>HEADER1</th><th>HEADER2</th><th>HEADER3</th><th>HEADER4</th></tr>
<tr><td>Row:1 Cell:1</td><td>Row:1 Cell:2</td><td>Row:1 Cell:3</td><td>Row:1 Cell:4</td></tr>
</table>

那么,有没有人可以建议我一个可以插入新内容的 sed cmd:

<tr><td>Row:1 Cell:1</td><td>Row:1 Cell:2</td><td>Row:1 Cell:3</td><td>Row:1 Cell:4</td>

就在标题下方?

谢谢!

最佳答案

首先,我们有一个包含以下几行的文件,名为 datafile.txt

1 some test lines here
but not all lines contain nubers
3 and here is the last one

我们有一个 bash 变量 $ADDED ,其中包含要添加的行内容

ADDED="==This is the new line=="

因此,在第一行之后添加行

ADDED="==This is the new line=="
< datafile.txt sed "1a \\
$ADDED
"

结果:

1 some test lines here
==This is the new line==
but not all lines contain nubers
3 and here is the last line

在所有以数字开头的行之后添加行

< datafile.txt sed "/^[0-9]/a \\
$ADDED
"

结果:

1 some test lines here
==This is the new line==
but not all lines contain nubers
3 and here is the last line
==This is the new line==

将行添加到开头,因此在第一行之前插入

< datafile.txt sed "1i \\
$ADDED
"

结果

==This is the new line==
1 some test lines here
but not all lines contain nubers
3 and here is the last line

您可以“替换”行尾以添加新行

< datafile.txt sed "/all/s/$/\\
$ADDED/"

上面的示例通过替换在包含单词“all”的行之后添加行

1 some test lines here
but not all lines contain nubers
==This is the new line==
3 and here is the last line

您甚至可以分割线并在之间添加

< datafile.txt sed "/all/s/\(.*lines \)\(.*\)/\1\\
$ADDED\\
\2/"

上面的代码将搜索包含单词“all”的行,并将其拆分在单词“lines”之后。结果:

1 some test lines here
but not all lines
==This is the new line==
contain nubers
3 and here is the last line

最后一件事。使用正则表达式解析 HTML 是不可能的,请检查 sputnik 评论中的链接。

但是,这并不意味着不可能匹配 HTML 文件的某些部分。如果你知道你想要什么匹配(而不是解析) - 你也可以安全地使用 HTML 的正则表达式。简单来说,这里很多人不知道解析和匹配之间的区别。

所以,如果您的 html 文件具有众所周知的结构,例如你确信你的html始终是上述结构,你可以放心地写:

<your_file.html sed "/^<tr><th>/a \\
<tr><td>new Row:1 Cell:1</td><td>Row:1 Cell:2</td><td>Row:1 Cell:3</td><td>Row:1 Cell:4</td>
"

你会得到

<table id="tfhover" class="tftable" border="1">
<tr><th>HEADER1</th><th>HEADER2</th><th>HEADER3</th><th>HEADER4</th></tr>
<tr><td>new Row:1 Cell:1</td><td>Row:1 Cell:2</td><td>Row:1 Cell:3</td><td>Row:1 Cell:4</td>
<tr><td>Row:1 Cell:1</td><td>Row:1 Cell:2</td><td>Row:1 Cell:3</td><td>Row:1 Cell:4</td></tr>
</table>

只是因为我们没有解析 html 代码,我们只是匹配一些线条模式。

关于linux - sed:在某个位置插入一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15555781/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com