1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

sedメモ

Last updated at Posted at 2024-10-19

記事の目的

運用保守の現場で使用したり先輩から学んだコマンドなどを知識の定着かつ辞書が割りに記録する。
もし見ていただいた方でより良い方法などあればご教授いただけると有り難いです。

sed

正規表現などを使い細かい条件の置換やファイルの編集をする事ができるコマンド。

基本構文

# 全ての文字列aを文字列bに置換する
$ sed 's/hoge/fuga/g' input.txt

# gを省くと最初に当てはまったものだけを置換する
$ sed 's/hoge/fuga/' input.txt

# catとパイプを使用してもできる
$ cat input.txt | sed 's/hoge/fuga/g'

# リダイレクトも可能
$ cat input.txt | sed 's/hoge/fuga/g' > output.txt

行末のカンマを改行に置換する

# input file
$ cat input.txt
aaa,bbb,ccc,ddd,

# 行末のカンマを改行に置換できる
$ sed 's/,$/\n/g' input.txt
aaa,bbb,ccc,ddd
 ←改行が入る

# 単純に削除するだけなら
$ sed 's/,$//g' input.txt
aaa,bbb,ccc,ddd

空白以外の文字列をシングルクオーテーションで囲む

# input file
$ cat input.txt
hoge
fuga

piyo

# []内の^は否定を表す。以下は空白以外という意味。([]外の^は行頭を表す)
# &はマッチした文字列自体を表す
$ sed "s/[^ ]\+/'&'/g" input.txt
'hoge'
'fuga'

'piyo'

特定のファイルをまとめてリネームする ※別記事で書き直しました

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?