1
0

More than 3 years have passed since last update.

sed で JSON の value を変更する

Last updated at Posted at 2020-04-11

sed コマンドとは

sed は入力ストリーム(ファイルまたはパイプラインからの入力)に対して、文字列を全置換したり、行単位で抽出したり、削除したり、いろいろなテキスト処理のできるコマンド。
処理内容はコマンドラインパラメータで指定して、非対話的に一括処理できる。
sed は「Stream EDitor」 の略。

今回はこの sed と使って、package.json の version を変更してみます。

単純に version を置換する

以下のような package.json があるとします。

{
  "name": "sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "qiita",
  "license": "ISC"
}

version を 1.0.0+1 に置換したい場合、sed コマンドを以下のよう使います。

sed -i -e "s/1.0.0/1.0.0+1/" package.json

オプション

  • -e script : スクリプト(コマンド)を追加する
  • -i : ファイルを直接編集する

置換対象を明示的に指定しない

置換対象の version(1.0.0) を条件に含めたくない場合はこんな感じ。

sed -i -e "s/\"version\":.*\"/\"version\": \"1.0.0+1\"/" package.json

もっと汎用的に置換したい

1.0.0+1 だけではなく、もっと柔軟に 2.0.0+1 とか 3.0.0+1 にも対応させたいよという場合は正規表現のキャプチャを使えばできます。

正規表現のキャプチャというのは、置換対象を \(と\) でくくると、後で \1 で取り出せる、というものです。複数、置換対象を \(と\) でくくると、\2, \3, \4 で取り出すことができます。

こんな感じです。

sed -i -e "s/\"version\": \"\(.*\)\"/\"version\": \"\1+1\"/" package.json
1
0
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
0