How to insert file content into another file?

49 views Asked by At

confi.ini (BEFORE)

[DEFAULT]
## Default settings ######################
debug = false

[app:main]
abc=def
ghfi=kftest

## General settings ######################
use=hello
test1.test2=test3

[logger]
level=INFO
handlers=console

extra_conf.ini

security.host=localhost
security.username=test
security.password=test12345

Can I know how do I use command to insert the extra_conf.ini file content into the confi.ini, under the [app.main]? I googled and found sed command, but I can't seem to do it as per the expected_confi.ini file, can someone please assist?

expected_confi.ini (AFTER changed)

[DEFAULT]
## Default settings ######################
debug = false

[app:main]
security.host=localhost
security.username=test
security.password=test12345
abc=def
ghfi=kftest

## General settings ######################
use=hello
test1.test2=test3

[logger]
level=INFO
handlers=console
2

There are 2 answers

0
Daniel Oliveira On

Yes, you can use sed to print just part of a file.

It's import to understand sed process one line at a time, printing the result. The basic usage is to match a string and execute a command.

So you can get your desired file by:

  1. Print lines from confi.ini, up to [app:main]:

    sed "/\[app:main\]/q" confi.ini, where the q command quits sed, so we're printing everything until finding [app:main].

  2. Print all lines from extra_conf.ini:

    cat extra_conf.ini

  3. Print lines from confi.ini, except the ones from the start to [app:main]:

    sed "1,/\[app:main\]/d" confi.ini, where the d command deletes lines 1 to the line with [app:main].

Redirecting to new_conf.ini and putting it all together in a single-line command.

sed "/\[app:main\]/q" confi.ini > new_conf.ini; cat extra_conf.ini >> new_conf.ini; sed "1,/\[app:main\]/d" confi.ini >> new_conf.ini

Be sure that extra_conf.ini has no line break at the end.

2
William Pursell On

Probably the simplest way to do this with sed is:

sed -e '/^\[app:main\]$/rextra_conf.ini' confi.ini > expected_confi.ini 

The pattern ^\[app:main\]$ matches the header of the section, and the r command reads the named file into the input stream. The command looks a little weird here, and the string rextra_conf.ini is the command r followed by the name of the file to be read into the stream.