如何读取一行,稍微修改并使用awk / sed将其写回?

时间:2013-03-21 19:55:13

标签: bash sed awk

我有一个以下格式的json文件:

[
    {
        "organization": "ABC", 
        "type": "School", 
        "contact": "Joe Schmo", 
        "contact_title": "Principal", 
        "mailing_address": "123 Main Street, Anytown, MA", 
        "phone": "214-555-5430",
        "fax": "214-555-5444"
    },
    {
        "organization": "XYZ",
        "type": "School",
        "contact": "John Doe", 
        "contact_title": "Asst Principal", 
        "mailing_address": "123 Main Street, Anycity, TX", 
        "phone": "512-555-5430",
        "fax": "512-555-5444"
    },
    .
    .
    .
    .
]

我想复制以"organization"开头的行,然后在用"organization""company"替换"long name"后将其重新添加回文件两次。我也想保留原线。 我想要的输出是:

[
    {
        "organization": "ABC",
        "company": "ABC",
        "long name": "ABC", 
        "type": "School", 
        "contact": "Joe Schmo", 
        "contact_title": "Principal", 
        "mailing_address": "123 Main Street, Anytown, MA", 
        "phone": "214-555-5430",
        "fax": "214-555-5444"
    },
    {
        "organization": "XYZ",
        "company": "XYZ",
        "name": "XYZ",
        "type": "School",
        "contact": "John Doe", 
        "contact_title": "Asst Principal", 
        "mailing_address": "123 Main Street, Anycity, TX", 
        "phone": "512-555-5430",
        "fax": "512-555-5444"
    },
    .
    .
    .
    .
]

awksed首选解决方案。

1 个答案:

答案 0 :(得分:4)

这是一种方式:

sed '/organization/p;s/organization/company/p;s/company/long name/' file

这是另一个:

awk '$1~/organization/{print $0;sub(/organization/,"company");print $0;sub(/company/,"long name")}1' file