Linuxテキスト処理コマンド

よく使うテキスト処理のコマンドメモです。

sed

※ファイルを上書きする場合はオプションを-eから-eiへ。

コメントアウト行(先頭#)を除いて表示かつ、空白行も除いて表示
sed -e 's/#.*//g' -e '/^ *$/d' /tmp/test.txt


複数スペースと1個スペースが混在する状態で、全て1個スペースに統一して表示
sed -e 's/  */ /g' /tmp/test.txt


タブを改行に置換して表示
sed -e "s/\\t/\\n/g" /tmp/test.txt


行の下に特定文字を追記して表示

/tmp/test.txtの
aaa
の下に
bbbを追記する例

sed -e "/aaa/ a  bbb" /tmp/test.txt


空白行を削除して表示
sed -e "/^$/d" /tmp/test.txt


先頭に文字を挿入して表示

先頭に『hoge』を挿入する例

sed -e "s/^/hoge/g" /tmp/test.txt


行末に文字を挿入して表示

行末に『hoge』を挿入する例

sed -e "s/$/hoge/g" /tmp/test.txt


tr

改行をスペースに置換して1行にする
cat /tmp/test.txt | tr '\n' ' '