Sed 将长单行注释转换为多个短行
我有几行很长的单行注释:Sed 将长单行注释转换为多个短行,sed,Sed,我有几行很长的单行注释: # this is a comment describing the function, let's pretend it's long. function whatever() { # this is an explanation of something that happens in here. do_something(); } 对于这个例子(将它调整到其他数字应该很简单),我想要 每行最多包含33个字符(每个缩进级别为4个空格),并且 在最后
# this is a comment describing the function, let's pretend it's long.
function whatever()
{
# this is an explanation of something that happens in here.
do_something();
}
对于这个例子(将它调整到其他数字应该很简单),我想要
# this is a comment describing
# the function, let's pretend
# it's long.
function whatever()
{
# this is an explanation of
# something that happens in
# here.
do_something();
}
我正试图为此编写一个sed
脚本,我的尝试是这样的(为了清晰起见,没有尝试在特定字符计数时使其中断,因为它不起作用):
这只会断线一次,而且不会像我错误地假设的那样重复执行g
(如果它只是s//\n/g
或什么的话,它实际上会这样做)
其模块满足您的需要:
perl -MText::Wrap='wrap,$columns' -pe '
s/^(\s*#)(.*)/$columns = 33 - length $1; wrap("$1", "$1 ", "$2")/e
' < input > output
perl-MText::Wrap='Wrap,$columns'-pe'
s/^(\s*#)(.*)/$columns=33-长度$1;换行(“1美元”、“1美元”、“2美元”)/e
“输出
使用具有给定参数的给定模块。在这里,我们将使用-M
函数和wrap
变量$columns
逐行读取输入并打印可能修改的行(如-p
)sed
是在替换部件中使用code的替换,匹配部件由代码返回的值替换s///e
- 为了计算宽度,我们从33中减去初始空白。如果您在源代码中使用制表符,则必须特别处理它们
采用三个参数:第一行的前缀,其余行的前缀(在本例中,它们几乎相同:注释前缀,我们只需要在第二行中添加空格),以及要换行的文本wrap
-length$1
部分即可
perl -MText::Wrap='wrap,$columns' -pe '
s/^(\s*#)(.*)/$columns = 33 - length $1; wrap("$1", "$1 ", "$2")/e
' < input > output