附加到每行的开头和结尾?

时间:2015-03-23 04:08:35

标签: sed

我正在开发一个创建HTML文件的sed脚本。我想在每行的开头和结尾添加段落标记,但无法弄清楚它是如何工作的。

现在我有以下sed脚本:

1i\
<html>\
<head><title>sed generated html</title></head>\
<body>\
<pre>
$a\
</pre>\
</body>\
</html>

我如何将<p></p>标记中的每一行括起来?

示例:

的test.txt

This is a test file.
This is another line in the test file.

使用sed脚本输出:

<html>
<head><title>sed generated html</title></head>
<body>
<pre>
<p>This is a test file.</p>
<p>This is another line in the test file.</p>
</pre>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

使用 sed

将您的脚本更改为:

1i\
<html>\
<head><title>sed generated html</title></head>\
<body>\
<pre>
s/.*/<p>&<\/p>/
$a\
</pre>\
</body>\
</html>

与您的命令相同,但添加了s/.*/<p>&<\/p>/。使用<p></p>围绕文件中的每一行。 使用命令sed -f script File

使用 awk

<强> cat script

BEGIN {
printf "<html>\n\
<head><title>sed generated html</title></head>\n\
<body>\n\
<pre>\n"
}
{print "<p>"$0"</p>"}
END {
printf "</pre>\n\
</body>\n\
</html>\n"
}

<强> cat File

This is a test file.
This is another line in the test file.

<强> Command:

awk -f script File

<强> Sample:

AMD$ awk -f script File
<html>
<head><title>sed generated html</title></head>
<body>
<pre>
<p>This is a test file.</p>
<p>This is another line in the test file.</p>
</pre>
</body>
</html>