sed(せど)の基本的な使い方を知っておくことで、データ編集をする際、作業効率をあげることができます。
今後も、この記事内の内容は、都度、拡充されると思います。
文字列を置き換える
$ cat textfile abc abcabc abc123 123abc 123123 $ cat textfile | sed -e "s/abc/xyz/" <= 行中にある最初の「abc」を「xyz」に置換する xyz xyzabc xyz123 123xyz 123123
$ cat textfile abc abcabc abc123 123abc 123123 $ cat textfile | sed -e "s/abc/xyz/g" <= 行中にある全ての「abc」を「xyz」に置換する xyz xyzxyz xyz123 123xyz 123123
$ cat textfile abc abcabc abc123 123abc 123123 $ cat textfile | sed -e "s/^abc/xyz/" <= 行中にある行頭の「abc」を「xyz」に置換する xyz xyzabc xyz123 123abc 123123
$ cat textfile abc abcabc abc123 123abc 123123 $ cat textfile | sed -e "s/abc$/xyz/" <= 行中にある行頭の「abc」を「xyz」に置換する xyz abcxyz abc123 123xyz 123123
パターンを指定して削除する
$ cat textfile abc abcabc abc123 123abc 123123 $ cat textfile | sed -e "/abc/d" <= 行中に「abc」があれば、その行を削除する 123123
$ cat textfile abc abcabc abc123 123abc 123123 $ cat textfile | sed -e "s/bc//" <= 行中にある最初の「bc」を削除する a aabc a123 123a 123123
$ cat textfile abc abcabc abc123 123abc 123123 $ cat textfile | sed -e "s/bc//g" <= 行中にある全ての「bc」を削除する a aa a123 123a 123123
コメント行と空行を削除する
「#」で始まるコメント行と空行を削除します。
$ cat textfile #abcdef abcdef #defghi defghi #ghijkl ghijkl $ cat textfile | sed -e "/^#/d" | sed -e "/^$/d" abcdef defghi ghijkl
改行コードの変換をする
$ file LF.txt LF.txt: ASCII text $ cat LF.txt | sed -e "s/$/\r/" > CRLF.txt.edited $ file CRLF.txt.edited CRLF.txt.edited: ASCII text, with CRLF line terminators $ cat CRLF.txt.edited | sed -e "s/\r//" > LF.txt.edited $ file LF.txt.edited LF.txt.edited: ASCII text
行番号を指定して削除する
$ cat textfile 1 2 3 4 5 $ cat textfile | sed -e "3d" 1 2 4 5 $ cat textfile | sed -e "2,4d" 1 5