首页 > 解决方案 > 如何替换括号之间的换行符

问题描述

我有类似这种格式的日志文件

test {
seq-cont {
                        0,
                        67,
                        266
                        },
                grp-id 505
        }
}
test{
        test1{
                val
        }
}

这是产生该输出的 echo 命令

$ echo -e "test {\nseq-cont {\n\t\t\t0,\n\t\t\t67,\n\t\t\t266\n\t\t\t},\n\t\tgrp-id 505\n\t}\n}\ntest{\n\ttest1{\n\t\tval\n\t}\n}\n"

问题是如何删除文件中可能是多个空格之间seq-cont {的所有空格。}

我希望输出是这样的。最好使用 sed 来产生输出。

test{seq-cont{0,67,266},
                       grp-id 505
        }
}
test{
        test1{
                val
        }
}

OP的努力:这是一个有点工作但不完全是我想要的:

sed ':a;N;/{/s/[[:space:]]\+//;/}/s/}/}/;ta;P;D' logfile

标签: linuxawksedgreplogfile

解决方案


可以使用匹配和关闭gnu-awk的自定义正则表达式来完成:RS{}

awk -v RS='{[^}]+}' 'NR==1 {gsub(/[[:space:]]+/, "", RT)} {ORS=RT} 1' file

test {seq-cont{0,67,266},
                grp-id 505
        }
}
test{
        test1{
                val
        }
}

这里:

  • NR==1 {gsub(/[[:space:]]+/, "", RT)}: 对于第一条记录,用空字符串替换所有空格(包括换行符)。
  • {ORS=RT}:设置ORS为我们捕获的任何文本RS

PS:NR==1如果要对整个文件执行此操作,请删除。


推荐阅读