在如下文件中:
ruler 1 2 3 4 5 6 7 8
12345678901234567890123456789012345678901234567890123456789012345678901234567890
\usage{
function(
parameter,
parameterparameter,
parameter = parameter,
parameter = p,
parameter = para,
parameter = para,
paramete = p,
parameterparameter = pa,
parameter = p,
p = pa,
param,
parameterpara = par,
paramet = par,
parameter = param,
parameterpa = param,
...
more lines
我想将“usage”行与“...”行连接起来,然后在第 80 个字符(列)之前的逗号后面创建新的换行符。
目前,我设法在第 n 个逗号之后换行,但效率不高,因为在许多情况下,在第三个逗号之后仍然留有很多空格。所以我希望换行符之前的逗号尽可能靠近第 80 个字符。
sed -i -r '/usage/{:a;N;/\.\.\./!ba;s/\n//g}' filename.txt
sed -i 's/\(\([^,]\+,\)\{3\}\)/\1\n/g;s/\n/\n/g' filename.txt
我查看了“par”、“fold”和“fmt”文档,但没有成功。 “fold” 接近但在空格中分割线而不是逗号:
sed -i -r '/usage/{:a;N;/\.\.\./!ba;s/\n//g}' filename.txt
fold -s filename.txt | tee filename.txt
答案1
使用awk
:
$ awk '/^\\usage/,/^\.\.\./ { if (length(line $0) >= 80) { print line; line = $0 } else line = line $0; next }; line != "" { print line; line = "" }; 1' file
1 2 3 4 5 6 7 8
12345678901234567890123456789012345678901234567890123456789012345678901234567890
\usage{function(parameter,parameterparameter,parameter = parameter,
parameter = p,parameter = para,parameter = para,paramete = p,
parameterparameter = pa,parameter = p,p = pa,param,parameterpara = par,
paramet = par,parameter = param,parameterpa = param,...
more lines
代码awk
,注释:
/^\\usage/,/^\.\.\./ {
# This block triggers for all lines between a line
# starting with "\usage" and another line
# starting with "..."
# If our saved output line and the current line together
# is longer or equal to 80 characters, print the output
# line and reset it to the current line. Else, add the
# current line to the end of the saved output line.
if (length(line $0) >= 80) {
print line
line = $0
} else
line = line $0
# Skip to next line of input.
next
}
# If we get here and the saved output line is
# non-empty, then there is data to output, so
# do that.
line != "" { print line; line = "" }
# Print all input.
1
答案2
一个懒惰的变体,使用 的perl
slurp 模式:
perl -0777 -pi -e '
s{\\usage.*?\n\.\.\.\n}{
($r = $&) =~ s/\n//g;
$r =~ s/\G.{0,79}(,|.$)\K/\n/g;
$r
}gse' your-file
这使:
1 2 3 4 5 6 7 8
12345678901234567890123456789012345678901234567890123456789012345678901234567890
\usage{function(parameter,parameterparameter,parameter = parameter,
parameter = p,parameter = para,parameter = para,paramete = p,
parameterparameter = pa,parameter = p,p = pa,param,parameterpara = par,
paramet = par,parameter = param,parameterpa = param,...
more lines