LoginSignup
0
0

More than 5 years have passed since last update.

bash / awk > ファイルに空行を入れる実装

Last updated at Posted at 2017-03-27
動作環境
Xeon E5-2620 v4 (8コア) x 2
32GB RAM
CentOS 6.8 (64bit)
openmpi-1.8.x86_64 とその-devel
mpich.x86_64 3.1-5.el6とその-devel
gcc version 4.4.7 (とgfortran)
NCAR Command Language Version 6.3.0
WRF v3.7.1を使用。
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) 
Python 3.6.0 on virtualenv
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

対象ファイル例

dat.txt
1
2
3
4
5
6
7
8
9
10

処理内容

上記のファイルにて、3行ずつ空行を入れる。
空行の入れる位置は1と2の間から始める。

実装1 > while read使用

参考: @magicant さんのコメント
参考: シェルをステップ実行したい @ 検索ではあんまり出ないbashの便利技

add_emptylines_everyNlines_170327a_exec
#!/usr/bin/env bash

infile=dat.txt
idx=0
while read -r line;do
    if [ $(( $idx % 3 )) -eq 1 ]; then
        echo 
    fi
    echo $line
    idx=$((idx+1))
done < $infile
結果
]$ bash add_emptylines_everyNlines_170327a_exec 
1

2
3
4

5
6
7

8
9
10

実装2 > IFS使用

参考: @kazu56 さんのコメント
参考: コメント

add_emptylines_everyNlines_170327b_exec
#!/usr/bin/env bash

IFS=$'\n'
lines=($(cat dat.txt))
numline=${#lines[@]}
for idx in $(seq 1 $numline);do
    if [ $(( $[idx-1] % 3 )) -eq 1 ]; then
        echo ""
    fi
    echo ${lines[idx-1]}
done
結果
$ bash add_emptylines_everyNlines_170327b_exec 
1

2
3
4

5
6
7

8
9
10

実装3 > awk

参考 http://stackoverflow.com/questions/977408/how-do-i-insert-a-blank-line-every-n-lines-using-awk

$ awk '{if((NR % 3) == 2){printf("\n")} ; print; }' dat.txt 
1

2
3
4

5
6
7

8
9
10

awkの方法はstackoverflowでいくつかあるが、記憶しておく事項が少ない上記の方法が自分には良い。

0
0
2

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