How to copy partial contents (specifically few sections denoted by square brackets) from one file to another with shell script?

I have one project’s .git/config file in which I have following contents:


    name = <FullName>
    email = <EmailID>
    username = <UserName>
[core]
    editor = nvim
    whitespace = fix,-indent-with-non-tab,trailing-space,cr-at-eol
    pager = delta
[web]
    browser = google-chrome
....
....
[alias]
    a = add --all
    ai = add -i
    #############
    ap = apply
    as = apply --stat
    ac = apply --check
....
....
[filter "lfs"]
    clean = git-lfs clean -- %f
    smudge = git-lfs smudge -- %f
    process = git-lfs filter-process
    required = true

Now I want to copy multiple sections and their contents like [alias], [filter "lfs"] etc. but not the and [web] sections from this .gitconfig file to another project’s (which is under same parent as this project’s directory) .gitconfig file.

Now I know I can loop thro’ and print lines of this file, but not idea how to write multiple sections to another file(with less code clutter as possible) such that it doesn’t overwrite target file’s original contents:

while read line || [ -n "$line" ]; do echo $line; done < $filename;

Help is much appreciated…

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

While you could do this via bash/awk, I’d recommend using an INI file parser.
For example, you can do the following in Python using configparser library:

import sys
import configparser

def print_section(conf, section):
    print("[{}]".format(section))
    for key in conf[section]:
        print("    {} = {}".format(key, conf[section][key]))


c = configparser.RawConfigParser()
c.read('config.ini')

sections = ['alias', 'filter "lfs"']
for s in sections:
    print_section(c, s)

Oneliner of the same:

printf "import sys; import configparser; c = configparser.RawConfigParser(); c.read('config.ini'); sections = ['alias', 'filter \"lfs\"'];\nfor s in sections:\n  print(\"[{}]\".format(s));\n  for key in c[s]:\n    print(\"    {} = {}\".format(key, c[s][key]))"  | python3

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply