【勉強メモ】sedコマンドの使い方
今週の風邪期間中、ほぼ寝てばっかだったが、
sedコマンドについて調べたことをメモっておく。
※主に、下記の本を参考に作成した。
ソフトバンククリエイティブ
売り上げランキング: 16,716
※""で囲った場合は変数を展開する
※タブは\tでOK
※同時に複数の変換処理をする際にeオプションが必要
■置換
・行で最初に出てきた文字列を置換
sed -e 's/foo/bar/' myfile.txt
・行全体を置換
sed -e 's/foo/bar/g' myfile.txt
・1-10行目の行全体を置換
sed -e '1,10s/enchantment/entrapment/g' myfile2.txt
・タブをスペースに変換
sed -e "s/\t/ /g" testfile
・5行目から最終行までを置換
【シングルクォートの場合】
sed -e '5,$s/OldText/NewText/g' samplefile
【ダブルクォートの場合】
sed -e "5,\$s/OldText/NewText/g" samplefile
※"の場合は$がシェルに変数と解釈されてしまうため
・実際の行数を超えて指定してもOK
sed -e "5,100s/OldText/NewText/g" samplefile
■削除
・文字列の削除
sed -e "s/TexttoRemove//g"
・「OldText」を含む行を削除して表示 (grep -v OldTextと同じ)
$ sed -e "/OldText/d" samplefile
・コメント行を削除
sed -e '/^#/d' samplefile
または sed -e "/^#/d" samplefile
・行頭の文字列を消す(行頭に「TexttoRemove」を含むもの)
sed -e "s/^TexttoRemove//"
・行頭の3文字を削除
sed "s/^...//g" samplefile
・行末の文字列を消す(行末に「TexttoRemove」を含むもの)
sed -e "s/TexttoRemove\$//"
・空白行(何も書かれていない行)を削除 (※行頭(^)と行末($)の間に何もない行)
※ただしtabやspaceだけの行は削除できない!
sed -e "/^$/d" testfile
・tabやspaceだけの行も含めて、空白行(何も書かれていない行)を削除
sed -e "/^[\t ]*$/d" testfile
■正規表現
・「OldText」を含む行を非表示にする(空行として表示)
$ sed -e "s/.*OldText.*//g" samplefile
mmmnnnn
-
-
- -
-
※比較:「OldText」を含む行を削除して表示 (grep -v OldTextと同じ)
$ sed -e "/OldText/d" samplefile
mmmnnnn
・行頭のタブを削除
sed -e "s/[\t]//g" testfile
・行頭のスペースを削除
sed -e "s/^ *//g" testfile
・スペースまたはタブを削除
sed -e "s/[\t ]//g" testfile
※[
・複数のスペースを1つのスペースに置換
sed -e "s/ */ /g" testfile
・タブやスペースが混在しているときに1つのスペースに置換
sed -e "s/[\t ][\t ]*/ /g" testfile
■指定行の削除
・3行目を削除
sed -e "3d"
・1-4行目を削除
sed -e "1,4d"
・最終行を削除
sed -e "\$d" または sed -e '$d'
■指定行の表示
※-nをつけると、指示した行だけを標準出力に出す 【必ずp(print)が必要】
・2-8行目までを表示
sed -n '2,8p' access_log
・42行目から最後まで
sed -n '42,$p' access_log
・置換処理を行った行だけを表示
sed -n -e s"s/OldText/NewText/gp" samplefile
■事例
$ cat fileaa | grep -n ".*"
1:xxxxxxxxxxxxx
2:Beginaaaaaaaaaaa
3:bbbbbbbbbbbbbbbb
4:cccccccccccccccc
5:ddddddEndddddddd
6:eeeeeeeeeeeee
・BeginとEndに囲まれた部分だけを削除
$ sed -e "2,5d" fileaa
xxxxxxxxxxxxx
eeeeeeeeeeeee
・BeginとEndに囲まれた部分だけを表示
$ sed -n "2,5p" fileaa
Beginaaaaaaaaaaa
bbbbbbbbbbbbbbbb
cccccccccccccccc
ddddddEndddddddd
・【キーワードによる指定】BeginとEndに囲まれた部分だけを削除(使えそう!)
$ sed -e "/Begin/,/End/d" fileaa
xxxxxxxxxxxxx
eeeeeeeeeeeee
・【キーワードによる指定】BeginとEndに囲まれた部分だけを表示(使えそう!)
$ sed -n "/Begin/,/End/p" fileaa
Beginaaaaaaaaaaa
bbbbbbbbbbbbbbbb
cccccccccccccccc
ddddddEndddddddd
■Tips
・デリミタとしては/以外に%なども利用可能(ぶっちゃけ何でもOK)
例:
$ cat samplefile
OldTextasidhausehuOldText
mmmnnnn
hashjOldTextadjaoisjdaoi
$ sed "s/^...//g" samplefile
TextasidhausehuOldText
nnnn
hjOldTextadjaoisjdaoi
$ sed "s%^...%%g" samplefile
TextasidhausehuOldText
nnnn
hjOldTextadjaoisjdaoi
$ sed "s|^...||g" samplefile
TextasidhausehuOldText
nnnn
hjOldTextadjaoisjdaoi