如何使用 shell/bash 将 txt 转换为 html 格式
How to convert txt into html format using shell/bash
我在文本文件中有以下数据:
Details_A
name: A1
Valid: A1_Value
name: A2
Valid: A2_Value
Details_A2
name: A2
Valid: A2_Value
name: A2
Valid: A2_Value
我正在尝试将其转换为下面的 html table:
详情
您可以像这样使用 awk
:
awk 'BEGIN {
x = 0;
print "<table border="1">"
}
{
if (NF == 1){
print "<tr ><td colspan="2">"$i"</td>";
print "</tr>"
} else {
if (x == 0){
x++;
print "<tr><td>"$i"</td>"
} else {
x = 0;
print "<td>"$i"</td></tr>"
}
}
}
END {
print "</table>"
}' input.txt > table.html
随意添加任何其他样式
对于 awk
的旧版本,您可以使用以下内容,在 2009-11-26 的 awk
实现上测试(来自 one-true-awk):
awk 'BEGIN {
x = 0;
y = 0;
print "<table border="1">"
}
{
for (i = 1; i<=NF ; i++){
if (NF == 1){
print "<tr ><td colspan="2">"$i"</td></tr>";
} else {
if (x == 0 && y == 0){
print "<tr><td>"$i" ";
x++;
}
else if (x == 0 && y == 1){
print "<td>"$i" ";
x++;
}
else if (x==(NF-1)){
x = 0;
y++;
if (y == 2){
y = 0;
print ""$i"</td></tr>";
}
else{
print ""$i"</td>";
}
}
else {
print ""$i" ";
x++;
}
}
}
}
END {
print "</table>"
}' input.txt > table.html
对于最后一个版本,x
在每个 space 定界符处递增,直到我们到达 NF-1
,这是最后一个单词,我们应该以 </td>
结尾。结束 </tr>
的决定取决于 y
的值,该值在每一行递增,并在达到最大计数 <td>
时重新初始化(此处为 2 <td>
每 <tr>
)
我在文本文件中有以下数据:
Details_A
name: A1
Valid: A1_Value
name: A2
Valid: A2_Value
Details_A2
name: A2
Valid: A2_Value
name: A2
Valid: A2_Value
我正在尝试将其转换为下面的 html table:
详情
您可以像这样使用 awk
:
awk 'BEGIN {
x = 0;
print "<table border="1">"
}
{
if (NF == 1){
print "<tr ><td colspan="2">"$i"</td>";
print "</tr>"
} else {
if (x == 0){
x++;
print "<tr><td>"$i"</td>"
} else {
x = 0;
print "<td>"$i"</td></tr>"
}
}
}
END {
print "</table>"
}' input.txt > table.html
随意添加任何其他样式
对于 awk
的旧版本,您可以使用以下内容,在 2009-11-26 的 awk
实现上测试(来自 one-true-awk):
awk 'BEGIN {
x = 0;
y = 0;
print "<table border="1">"
}
{
for (i = 1; i<=NF ; i++){
if (NF == 1){
print "<tr ><td colspan="2">"$i"</td></tr>";
} else {
if (x == 0 && y == 0){
print "<tr><td>"$i" ";
x++;
}
else if (x == 0 && y == 1){
print "<td>"$i" ";
x++;
}
else if (x==(NF-1)){
x = 0;
y++;
if (y == 2){
y = 0;
print ""$i"</td></tr>";
}
else{
print ""$i"</td>";
}
}
else {
print ""$i" ";
x++;
}
}
}
}
END {
print "</table>"
}' input.txt > table.html
对于最后一个版本,x
在每个 space 定界符处递增,直到我们到达 NF-1
,这是最后一个单词,我们应该以 </td>
结尾。结束 </tr>
的决定取决于 y
的值,该值在每一行递增,并在达到最大计数 <td>
时重新初始化(此处为 2 <td>
每 <tr>
)