You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Perl实现文件行列对齐并跳过指定行的技术需求

处理my_file.txt表格列对齐的后处理方案

可以用awk编写脚本完成格式调整,既保留前3行和第一列的内容不变,又能将后续表格的列对齐成你需要的样式。

命令行直接执行版本

将以下命令复制到终端运行,处理后的内容会输出到formatted_my_file.txt:

awk '
# 保留前3行原样输出
NR <= 3 { print; next }
# 处理分隔线(全为短横线的行)
/^-+$/ { print; next }
# 处理Type开头的表头行
/^Type/ {
    printf "%-6s", $1
    printf "%-12s%-12s%-12s%-12s%-12s\n", $2, $3, $4, $5, $6
    next
}
# 处理T1/T2开头的子表头行
/^T[12]/ {
    printf "%-6s", $1
    idx = 2
    while (idx <= NF) {
        printf "%-5s%-7s", $idx, $(idx+1)
        idx += 2
    }
    print ""
    next
}
# 处理数值数据行
{
    printf "%-6s", $1
    idx = 2
    while (idx <= NF) {
        printf "%-5s%-7s", $idx, $(idx+1)
        idx += 2
    }
    print ""
}
' my_file.txt > formatted_my_file.txt

脚本文件版本

如果需要重复使用,可将以下内容保存为format_table.awk:

#!/usr/bin/awk -f

# 保留前3行原样输出
NR <= 3 { print; next }

# 处理分隔线(全为短横线的行)
/^-+$/ { print; next }

# 处理Type开头的表头行
/^Type/ {
    printf "%-6s", $1
    printf "%-12s%-12s%-12s%-12s%-12s\n", $2, $3, $4, $5, $6
    next
}

# 处理T1/T2开头的子表头行
/^T[12]/ {
    printf "%-6s", $1
    idx = 2
    while (idx <= NF) {
        printf "%-5s%-7s", $idx, $(idx+1)
        idx += 2
    }
    print ""
    next
}

# 处理数值数据行
{
    printf "%-6s", $1
    idx = 2
    while (idx <= NF) {
        printf "%-5s%-7s", $idx, $(idx+1)
        idx += 2
    }
    print ""
}

然后赋予执行权限并运行:

chmod +x format_table.awk
./format_table.awk my_file.txt > formatted_my_file.txt

效果说明

  • 严格保留原文件前3行和第一列(Type、T1、T2)的内容与格式
  • 将每个动物类别(Bird、Mammal等)对应的Age/Weight列按固定宽度对齐,保证表格整齐

内容的提问来源于stack exchange,提问作者oilfreedata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 11:45:55