最近sedをよく使っています。既存のファイルに定型的な処理を施す場合に便利ですね。
最近よく使う用法をメモ。
確認環境
[hoge@localhost ~]$ cat /etc/*-release CentOS Linux release 7.6.1810 (Core) [hoge@localhost ~]$ sed --version sed (GNU sed) 4.2.2
最近よく使うファイル操作
# テスト用のファイルを作成(1行目:1~5行目:5の5行のファイル) [hoge@localhost ~]$ seq 1 5 > 0105.txt [hoge@localhost ~]$ cat 0105.txt 1 2 3 4 5 # 1行目に「0」を挿入 # 1i0のようにクオートでくくらなくても良いし、シングルクオートや、ダブルクオートでくくっても良い [hoge@localhost ~]$ sed "1i0" 0105.txt 0 1 2 3 4 5 # 2行目に「1.5」を挿入 [hoge@localhost ~]$ sed "2i1.5" 0105.txt 1 1.5 2 3 4 5 # 3行目を削除 [hoge@localhost ~]$ sed "3d" 0105.txt 1 2 4 5 # 末尾行に「6」を挿入 # 「$(末尾行を示す)」を扱う場合は # 1.シングルクオートでくくる # 2.ダブルクオートでくくる&「\」でエスケープする [hoge@localhost ~]$ sed "\$a6" 0105.txt 1 2 3 4 5 6 # 末尾行を削除 # 「$(末尾行を示す)」を扱う場合は # 1.シングルクオートでくくる # 2.ダブルクオートでくくる&「\」でエスケープする [hoge@localhost ~]$ sed "\$d" 0105.txt 1 2 3 4 # 2行目に4行を挿入 # 改行を含む場合は改行文字として「\n」を入れる [hoge@localhost ~]$ sed "2i1.2\n1.4\n1.6\n1.8" 0105.txt 1 1.2 1.4 1.6 1.8 2 3 4 5