简体   繁体   中英

How to I read a line, modify it slightly and write it back using awk/sed?

I have a json file of the following format:

[
    {
        "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"
    },
    .
    .
    .
    .
]

I want to duplicate the line starting with "organization" and then add it back to the file twice after replacing "organization" with "company" and "long name" . I want to keep the original line too. The output I want is:

[
    {
        "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"
    },
    .
    .
    .
    .
]

awk or sed solutions preferred.

Here is one way:

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

Here is another:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM