如果使用 awk 的长度大于 7,如何将一行拆分为两行?

Sar*_*rah 2 sed awk text-processing

例如,我只想在命令行中打印类似的内容。假设我有一个名为 file.txt 的文件。

 What is life?
 how are you?
 hi
 whatup
 this is more than
Run Code Online (Sandbox Code Playgroud)

我想使用 awk 在命令行上打印出来,但如果字符数大于 7,那么输出应该是这样的。

 What is 
 life?
 how are 
 you?
 hi
 whatup
 this is
 more than
Run Code Online (Sandbox Code Playgroud)

所以基本上当我使用 awk 时,如果字符数大于 7,它会将输出中的行分成两行。

ter*_*don 10

虽然您可以在awk以下位置执行此操作:

$ awk '{sub(/.{8}/,"&\n"); print}' file
What is
life?
how are
you?
hi
whatup
this is
more than
Run Code Online (Sandbox Code Playgroud)

它确实不是这项工作的最佳工具。你可以更简单地做同样的事情:

$ fold -sw 8 file
What is 
life?
how are 
you?
hi
whatup
this is 
more 
than
Run Code Online (Sandbox Code Playgroud)

你也可以使用 Perl:

$ perl -pe 's/.{8}/$&\n/' file
What is 
life?
how are 
you?
hi
whatup
this is 
more than
Run Code Online (Sandbox Code Playgroud)


roa*_*ima 6

您可以使用awk,如其他答案中提供的那样,但您也可以使用fmt

fmt -s -w8 file
What is
life?
how are
you?
hi
whatup
this
is more
than
Run Code Online (Sandbox Code Playgroud)