【Shell】shellスクリプトjson内のフィールドの値を変更する

3192 ワード

shellスクリプトjsonのフィールドの値を変更する
  • 構想:awkによって古いデータを見つけ、古いデータ
  • をsedで置き換える
  • https://download.csdn.net/download/ly1414725328/10744793

  • ソースコード
    config.json
    {
      "name": "the_name",
      "id": "132869",
      "content_url": "https://hot.example.com/",
      "enable_feature1": "true",
      "enable_feature2": "false"
    }
    

    config/mode1.sh
    #!bin/bash
    content_url_new="https://hot1.example.com/"
    enable_feature1_new="true"
    enable_feature2_new="true"
    

    config/mode2.sh
    #!bin/bash
    content_url_new="https://hot2.example.com/"
    enable_feature1_new="false"
    enable_feature2_new="false"
    

    main.sh
    #!bin/bash
    
    if [ "$1" != "mode1" -a "$1" != "mode2" ];then
        echo "tip:─┬───────        ,   :" 
        echo "     │─────── 'mode1',   config/mode1.sh   "
        echo "     └─────── 'mode2',   config/mode2.sh   "
        exit 0
    fi
    
    case $1 in
    mode1) 
        . config/mode1.sh
    ;;
    mode2) 
        . config/mode2.sh
    ;;
    *)
        echo "Usage: sh main.sh [mode1|mode2]"
        exit;
    esac
    
    #               ,       
    content_url_old=$(awk -F"\"" '/content_url/{print $4}' example.json)
    sed -e "s@$content_url_old@$content_url_new@g" -i example.json
    
    
    #                ,           。(  ,              )
    enable_feature1_line=$(awk -F"\"" '/enable_feature1/{print NR}' example.json) #     
    enable_feature1_old=$(awk -F"\"" '/enable_feature1/{print $4}' example.json)  #      
    sed -e "$enable_feature1_line s@$enable_feature1_old@$enable_feature1_new@" -i example.json #          
    
    enable_feature2_line=$(awk -F"\"" '/enable_feature2/{print NR}' example.json) #     
    enable_feature2_old=$(awk -F"\"" '/enable_feature2/{print $4}' example.json)  #      
    sed -e "$enable_feature2_line s@$enable_feature2_old@$enable_feature2_new@" -i example.json #          
    

    うんてん
    sh main.sh mode1
    sh main.sh mode2
    

    その他のシナリオ
  • shellでjsonで指定した値を置き換える-矮子階段を登る-ブログ園
    sed -i  's/\("enable_feature1":"\).*/\1'"$enable_feature1_to"'",/g'   example.json