硬包装硬笔芯

硬包装硬笔芯

给定这个文件:

$ cat file
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike
november oscar papa quebec romeo sierra tango
uniform_victor_whiskey_xray yankee zulu

我想在70岁的时候努力突破,但我也想努力补充。我尝试了“折叠”,但它没有重新填充:

$ fold -w 70 file
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
a mike
november oscar papa quebec romeo sierra tango
uniform_victor_whiskey_xray yankee zulu

“fmt”会重新填充,但我只能让它在空格上中断,所以不能保证正好 70 换行:

$ fmt file
alfa bravo charlie delta echo foxtrot golf hotel india juliet
kilo lima mike november oscar papa quebec romeo sierra tango
uniform_victor_whiskey_xray yankee zulu

我尝试了“pr”,但它似乎只是截断了该行而不换行:

$ pr -t -W 70 file
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
november oscar papa quebec romeo sierra tango
uniform_victor_whiskey_xray yankee zulu

也许这些命令有一些我缺少的选项,或者可能是 Awk 或 Sed 解决方案。我宁愿避免较重的解决方案(Perl PHP Ruby)。

答案1

使用 sed

使用 GNU sed:

$ sed -zE 's/\n/ /g; s/.{70}/&\n/g; s/$/\n/' file
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
a mike november oscar papa quebec romeo sierra tango uniform_victor_wh
iskey_xray yankee zulu 

对于任何 POSIX sed:

sed -zE 'H;1h;$!d;x; s/\n/ /g; s/.{70}/&\n/g; s/$/\n/' file

使用 awk

$ awk  '{r=(length(r)?r" "$0:$0); while(length(r)>70){print substr(r,1,70); r=substr(r,71)}} END{print r}' file
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
a mike november oscar papa quebec romeo sierra tango uniform_victor_wh
iskey_xray yankee zulu

与 tr 和折叠

$ tr '\n' ' ' <file | fold -w 70
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
a mike november oscar papa quebec romeo sierra tango uniform_victor_wh
iskey_xray yankee zulu

上面的代码不会产生尾随换行符,但我们可以根据需要添加一个换行符echo ""

tr '\n' ' ' <file | fold -w 70; echo

答案2

这并不适用于所有情况,但它应该涵盖大多数用例:

$ fmt -w 2500 file | fold -w 70
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
a mike november oscar papa quebec romeo sierra tango uniform_victor_wh
iskey_xray yankee zulu

相关内容