查找不以“<", perform action

问题描述 投票:0回答:5

我正在使用 vim,并且有一个大文本文件,其中包含 some html。我正在尝试为网络做好准备,需要将

<p></p>
标签添加到尚未格式化的行中。这是我所拥有的一个例子:

Paragraph text one one line [... more ... ]
Other paragraph text on the next line [... more ... ]  
<h1>html element thrown in on its own line</h1>
More paragraph text [... more ... ]  
<!-- some other element (always own line) -->
There is still more text!

我正在寻找一种方法来搜索

<
字符开头的行,并且对于这些行,添加开始和结束
<p></p>
标签......这样,之后,我的文件类似于这个:

<p>Paragraph text one one line [... more ... ] </p>
<p>Other paragraph text on the next line [... more ... ]   </p>
<h1>html element thrown in on its own line</h1>
<p>More paragraph text [... more ... ]   </p>
<!-- some other element (always own line ) -->
<p>There is still more text! </p>

如何找到与起始

<
字符匹配的行?

regex vim sed
5个回答
12
投票
^([^<].*)$

确保您的选项不允许“点匹配换行符”并替换为:

<p>$1</p>

Vim 要求你转义某些字符,但我实际上没有 Vim,所以这是我对整个规则的最佳猜测:

s:^\([^<].*\)$:<p>\1</p>:g

2
投票
:%s/^[^<].*/<p>&<\/p>/

或者:

:v/^</s#.*#<p>&</p>#

这就是所需要的。


1
投票

这是逻辑。浏览文件,检查行开头是否有

<
,如果不存在,则使用
<p>
</p>
构造一个新字符串并将其回显。真的不需要复杂的正则表达式

用bash

#!/bin/bash
shopt -s extglob
while read -r line
do
    case "$line" in
        "<"*) echo $line ;;
        *) echo "<p>$line</p>";;
    esac   
done <"file"

使用awk

$ awk '!/^</{$0="<p>"$0"</p>"}{print}' file

输出

$ awk '!/^</{$0="<p>"$0"</p>"}1' file
<p>Paragraph text one one line [... more ... ]</p>
<p>Other paragraph text on the next line [... more ... ]  </p>
<h1>html element thrown in on its own line</h1>
<p>More paragraph text [... more ... ]  </p>
<!-- some other element (always own line) -->
<p>There is still more text!</p>

0
投票

这应该有效:

:%s/^\s*[^<]\+$/<p>&<\/p>/g

0
投票

另一种方法:

:v/^</normal I<p>^O$</p>

^O 实际上是按 CTRL+o 完成的

或者,如果您使用 surround.vim 插件:

:v/^</normal yss<p>
© www.soinside.com 2019 - 2024. All rights reserved.