仅更改文件中的特定部分,并跳过其他部分 [英] Change only a particular section in a file and skip the other sections

查看:52
本文介绍了仅更改文件中的特定部分,并跳过其他部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想更改文件的某个部分,如下所示:

I want to change only a certain section of a file that looks like this:

{
   "Section_A": {
    "ws/abc-Location01": 24, 
    "ws/abc-Location02": 67,
    "ws/abc-Location03:  101,
   },
   "Section_B": {
    "ws/abc-Location01": 33, 
    "ws/abc-Location02": 59,
    "ws/abc-Location03:  92,
   }
}

我只想根据外壳脚本中位置名称与数组的匹配情况,仅更改B节中字段2中的数值.

I want to change ONLY the numeric values in field 2 in Section B, based on match on the location name with an array, from a shell script.

例如,如果脚本中的数组中存在ws/abc-Location01,则不应更改其值,否则应将其值更改为file1.txt中第二个字段的值,其中第一个字段包含位置名称(如ws/abc-Location01)

For example, if ws/abc-Location01 is present in my array in my script, its value should not be changed, else its value should be changed to the value of the 2nd field in file1.txt, where the 1st field contains location name (like ws/abc-Location01)

我不确定该怎么做,因为给定的位置名称出现在每个部分中.那么如何告诉脚本忽略A节,C节等,而只更改B节中的值?

I'm not sure how to go about this, since a given location name occurs in each section. So how do I tell my script to ignore Section A, Section C and so on, and just change the value in Section B?

推荐答案

假设您的文件是正确的JSON(示例文件中的情况似乎不是 ,但是您已在注释),几行您喜欢的脚本语言就足够了.

Assuming your file is proper JSON (it does not seems to be the case in your sample file -- but you confirmed it in a comment), a few lines of your favorite script language should be sufficient.

就我而言,我使用Python:

As of myself, I used Python:

import sys
import json

data = json.load(sys.stdin)
data["Section_B"]["ws/abc-Location02"] = 9999
json.dump(data, sys.stdout,indent=True)

假设该文件存储为"change.py"

Assuming that file stored as "change.py"

# Original data (proper JSON)
$ cat data.json 
{
   "Section_A": {
    "ws/abc-Location01": 24, 
    "ws/abc-Location02": 67,
    "ws/abc-Location03": 101
   },
   "Section_B": {
    "ws/abc-Location01": 33, 
    "ws/abc-Location02": 59,
    "ws/abc-Location03": 92
   }
}

# Pipe original data to our filter
$ cat data.json | python change.py 
{
 "Section_A": {
  "ws/abc-Location01": 24, 
  "ws/abc-Location02": 67, 
  "ws/abc-Location03": 101
 }, 
 "Section_B": {
  "ws/abc-Location01": 33, 
  "ws/abc-Location02": 9999, 
  "ws/abc-Location03": 92
 }
}


如果只想使用shell解决方案,那么sed可能就足够了:


If you want a shell only solution, sed might be sufficient:

cat data.json | sed '/Section_B/,/}/{/Location02/s/:[^,]*/ 9999/}'

这显然要短一些;但也更脆弱... 从好的方面来说,这将处理类似JSON的文件以及正确的JSON(假定格式与您的示例相同).

This is obviously shorter; but much more fragile too... On the bright side, this will process JSON-like files as well a proper JSON (assuming formated as in your example).

这篇关于仅更改文件中的特定部分,并跳过其他部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆