Text-Formatting
在逗號之後創建換行符 - 在所需的行寬之前
在像這樣的文件中:
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 個逗號之後換行,但它效率不高,因為在許多情況下,在第 3 個逗號之後會留下很多空格。所以我希望換行符前的逗號盡可能接近第 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”文件,但沒有成功。“折疊”接近但在空格中分割行而不是逗號:
sed -i -r '/usage/{:a;N;/\.\.\./!ba;s/\n//g}' filename.txt fold -s filename.txt | tee filename.txt
一個惰性變體,使用
perl
’s 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
使用
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