![長さが7より大きい場合、awkを使用して1行を2行に分割するにはどうすればよいですか? [閉鎖]](https://linux33.com/image/88186/%E9%95%B7%E3%81%95%E3%81%8C7%E3%82%88%E3%82%8A%E5%A4%A7%E3%81%8D%E3%81%84%E5%A0%B4%E5%90%88%E3%80%81awk%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%A61%E8%A1%8C%E3%82%922%E8%A1%8C%E3%81%AB%E5%88%86%E5%89%B2%E3%81%99%E3%82%8B%E3%81%AB%E3%81%AF%E3%81%A9%E3%81%86%E3%81%99%E3%82%8C%E3%81%B0%E3%82%88%E3%81%84%E3%81%A7%E3%81%99%E3%81%8B%3F%20%5B%E9%96%89%E9%8E%96%5D.png)
たとえば、コマンドラインからこのような内容を印刷したいとします。 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より大きい場合、出力から行を2行に分割します。
答え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番目の文字が常に空白なので機能します。
8 番目の文字に関係なく、7 番目の文字で中断するには、次のようにします。
$ sed -e 's/./\
&/8' <file