0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ファイルの内容を複数行ごとにまとめて1行にしたい

Posted at

はじめに

普段あまりLinuxコマンドを利用しないのですが、ワンライナーでテキストを複数行ごとにまとめて1行にできたのでメモ

ユースケース

ファイルが何らかの事情によりこんな感じで複数行になってしまっているのを

src.txt
header1,
header2,
header3,
dataA1,
dataA2,
dataA3,
dataB1,
dataB2,
dataB3,

こうしたい場合のTips

dst.txt
header1,header2,header3,
dataA1,dataA2,dataA3,
dataB1,dataB2,dataB3,

コマンド

cat src.txt | awk '{if(NR%3)ORS="";else ORS="\n";print}' > dst.txt

解説

catコマンドを利用しsrc.txtの内容を出力し、それをパイプを利用してawkの入力とする。
awkのコマンドにより3の倍数の時だけ改行文字を挿入し、それ以外の場合には改行文字を入れずに出力する。それをdst.txtに出力する。

補足

Windows環境で作成されたファイルの場合は改行コードに\rが入っているため、思い通りにいかない。
その場合は以下のようにtrで\rを削除した上で実行すればOK

tr -d \\r < src.txt | awk '{if(NR%3)ORS="";else ORS="\n";print}' > dst.txt
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?