Thorbear
Thorbear

Reputation: 123

How to insert a string into a line in a file after a key word in bash

I have a file with some lines.

Lines.txt

value1
value2
value3

And I would like to append the lines in the file into another file after a key word.

AnotherFile.txt

NotTheKeyWord SomeOtherStuff SomeOtherStuff
NotTheKeyWord THEKEYWORD SomeOtherStuff SomeOtherStuff

I think sed has what I need, but I am having issues figuring out how to insert the text into the middle of the line.

And I want the result of:

AnotherFile.txt

NotTheKeyWord SomeOtherStuff SomeOtherStuff
NotTheKeyWord THEKEYWORD value1 value2 value3 SomeOtherStuff SomeOtherStuff

Upvotes: 1

Views: 2280

Answers (1)

0stone0
0stone0

Reputation: 44093

A pure solution:

sed -r "s:(THEKEYWORD):\1 $(sed ':a;N;$!ba;s/\n/ /g' test.txt) :g" insert.txt

Where;

  • test.txt is the value to be inserted, $(sed ':a;N;$!ba;s/\n/ /g' test.txt) removes any newlines from the file, so it can be inserted on the same line
  • insert.txt the text file where THEKEYWORD exists

If you wish to replace the file, use the -i option;

sed -i -r "s:(THEKEYWORD):\1 $(gsed ':a;N;$!ba;s/\n/ /g' test.txt) :g" insert.txt

As @KamilCuk pointed out, using paste -sd ' ' test.txt could be used to remove the newlines, and insert the file;

sed -r "s:(THEKEYWORD):\1 $(paste -sd ' ' test.txt) :g" insert.txt

Terminal output + sed version

Upvotes: 1

Related Questions