You almost never want to store the complete contents of a file in a variable in a Unix shell script. If you find yourself doing that, ask yourself whether there's another solution. If you can't find one on your own, come here and we'll look at it :-)
$ sed '/propertie/r file.txt' exam.txt
I am expert linux man
what we can do for out country
I love redhat machine
"propertie"
324325
5326436
3245235
646346
545
643
6436
63525
664
46454
centos less then redhat
fedore what
my name is moon yea
The r
("read") command in sed
takes a filename as its argument and inserts the file's content into the current stream.
If you need the added content indented, then make sure that the content of file.txt
is indented before running sed
:
$ sed 's/^/ /' file.txt >file-ind.txt
$ sed '/propertie/r file-ind.txt' exam.txt
I am expert linux man
what we can do for out country
I love redhat machine
"propertie"
324325
5326436
3245235
646346
545
643
6436
63525
664
46454
centos less then redhat
fedore what
my name is moon yea
With ed
(calling sed
for the indentation of the inserted file). This also does in-place editing of the file and replaces the original with the modified contents.
ed -s exam.txt <<END_ED
/propertie/r !sed 's/^/ /' file.txt
wq
END_ED
The r
command in ed
is able to read the output of an external command if the command is prefixed with !
. We use this to indent the data that we'd like to insert. It is otherwise, for obvious reasons, very similar to the sed
solution above.
The only downside with using ed
is that you can't generally use it on very large files. sed
is for editing streams of undetermined lengths, while ed
is ok for editing documents that you could see yourself opening in any other editor, i.e. not files of many megabytes or gigabytes in size.
ed
because i could use an interpolated variable kind of like this, but couldn't do it withsed
approached -s /opt/${FOLDER}/exam.txt <<END_ED /propertie/r !sed 's/^/ /' file.txt wq END_ED
– Luke Schoen May 18 '23 at 22:40