Ajim Bagwan
Ajim Bagwan

Reputation: 137

How to use sed command to add the contents of a command output at a particular position in a file?

I have following file.

cat addtext
This is sparta. 
Bye.

cat mainfile
abc
pqr

I want my output to look like -

This is sparta. 
abc
pqr
Bye.

i.e. the contents of first file added from the 2nd line of another file. I am trying this using sed command.

sed -i '1s/^/$filecontent\n/' abc.test

where

filecontent=`cat addtext`

But it is not replacing the value of variable and appending the value $filecontent instead of what it contents i.e contents of addtext file. How do I resolve this? How do we use other commands inside sed?

Upvotes: 0

Views: 91

Answers (2)

NeronLeVelu
NeronLeVelu

Reputation: 10039

LineWhere=1
File2Insert=addtext
File2Modify=mainfile

sed "${LineWhere} r ${File2Insert}" ${File2Modify} > DestinationFile

Action is to r read a file when at line specified. Variable are just here to show how to and be generic (double quote mandatory in this case)

Upvotes: 1

anubhava
anubhava

Reputation: 785551

You don't need sed just use cat:

cat file2 fil1

Equivalent sed command:

sed '' file2 file1

Or to insert content of file2 in file1 after line 1 use:

sed '1 r file2' file1

Upvotes: 2

Related Questions