在如下文件中:
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