shell腳本修改json中某個字段的值


shell腳本修改json中某個字段的值

  • 思路:通過awk來找到舊數據,然后用sed來替換舊數據

源碼

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

其他方案


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM