1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【初心者向け】しまさんのLinuxコマンドドリル sed編(解説付き)

Posted at

問題①

sample.txtの各行の先頭にある「#」を削除するには?

回答 sed 's/^#//' sample.txt

解説:
「^」は行頭を意味し、 「s/^#/」は「行頭の # を空文字に置換」します。

問題②

sample.txtの各行の末尾にある「.」を削除するには?

回答 sed 's/\.$//' sample.txt

解説:
バックスラッシュは「.(ドット)」をエスケープし、 $は行末を意味します。

問題③

sample.txt内の「apple」を「orange」にすべて置換するには?

回答 sed 's/apple/orange/g' sample.txt

解説:
「g」オプションで1行に複数ある「apple」もすべて置換されます。

問題④

sample.txtの3行目だけを表示するには?

回答 sed -n '3p' sample.txt

解説:
「-n」で出力を抑制し、「3p」 で3行目だけを表示します。

問題⑤

sample.txtの2〜4行目を削除するには?

回答

sed '2,4d' sample.txt

解説:
「d」は削除、「2,4」 は範囲指定です。

問題⑥

sample.txtの空行(何も書かれていない行)を削除するには?

回答

sed '/^$/d' sample.txt

解説:
「^$」は「行頭から行末まで何もない=空行」を意味します。

問題⑦

sample.txtの先頭に「●」を追加するには?

回答

sed 's/^/●/' sample.txt

解説:
「^」は行頭、そこに「●」を追加しています。

問題⑧

sample.txtの5行目を「Hello」に置き換えるには?

回答

sed '5cHello' sample.txt

解説:
「5c」は5行目を「Hello」に変更するコマンドです。

問題⑨

sample.txt内の英数字(a〜z, A〜Z, 0〜9)をすべて「*」に置換するには?

回答

sed 's/[a-zA-Z0-9]/*/g' sample.txt

解説:
[a-zA-Z0-9]は英数字の集合、 「g」で全て置換します。

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?