例如,我只想在命令行中打印类似的内容。假设我有一个名为 file.txt 的文件。
What is life?
how are you?
hi
whatup
this is more than
我想使用 awk 在命令行上打印出来,但如果字符数大于 7,那么输出应该如下所示。
What is
life?
how are
you?
hi
whatup
this is
more than
所以基本上当我使用 awk 时,如果字符数大于 7,它会在输出上将该行分成两行。
答案1
虽然您可以在以下位置执行此操作awk
:
$ awk '{sub(/.{8}/,"&\n"); print}' file
What is
life?
how are
you?
hi
whatup
this is
more than
它确实不是完成这项工作的最佳工具。您可以更简单地执行相同的操作:
$ fold -sw 8 file
What is
life?
how are
you?
hi
whatup
this is
more
than
您还可以使用 Perl:
$ perl -pe 's/.{8}/$&\n/' file
What is
life?
how are
you?
hi
whatup
this is
more than
答案2
您可以使用awk
,如其他答案中提供的那样,但您也可以使用fmt
fmt -s -w8 file
What is
life?
how are
you?
hi
whatup
this
is more
than
答案3
和
awk 'length < 7 { print ; next ; }
{ printf "%s\n%s\n",substr($0,0,7),substr($0,8) }' file.txt
结果是
What is
life?
how are
you?
hi
whatup
this is
more than
跳过白色字符的使用
awk 'length < 7 { print ; next ; }
{ printf "%s\n",substr($0,0,7) ;
i=8 ; while (substr($0,i,1) == " " ) i++; printf "%s\n",substr($0,i) }'
答案4
要获得您想要的输出sed
:
$ sed -e 's/.\{7\} /&\
/' <file
What is
life?
how are
you?
hi
whatup
this is
more than
因为输入中的第 8 个字符始终是空格,所以这就成功了。
如果您想在第 7 个字符处中断,而不考虑第 8 个字符:
$ sed -e 's/./\
&/8' <file