How to insert a new string after a text in a .txt document using bash?

I want to insert a particular string of text in an already existing text document using a bash command line. Let us say for example i have a text document named test.txt and contains the following text -

hi everyone
my name is 

i want to update the test.txt document in real time with same name to get this -

Hi everyone 
my name is 

I have tried using sed but for some reason it cant update the .txt with the same name. I also used sed with -i tag but i get an empty document after executing the code.

Any help would be appreciated,
Thank you

The easiest way I can think of is using shell redirection.

echo 'Shinty' >> test.txt

A single > sign redirects the output and overwrites the contents of the file, but double >> signs appends to it instead.

1 Like

hmm i should have phrased my question properly, i dont want it to append but rather be between 2 strings. Is that possible?

I assume you meant

hi everyone
is my name

and you want to put your name in between those lines. You can do it in a number of ways, but it’ll all be dependent on either the contents or the line.

I don’t like using sed -i, because it’s what I call bashism (technically gnu-ism and it’s not compatible with BSD sed), so I always use temporary files.

sed 's/everyone/everyone\nShinty/' testfile.txt > testfile.tmp.txt
mv testfile.tmp.txt testfile.txt

In bashism, you just remove the output redirect and the tmp file with the -i flag in sed.

sed -i 's/everyone/everyone\nShinty/' testfile.txt

If you know you want to put the name on line 2, then you don’t have to look for the word “everyone” and replace it, you can just sed number.

sed '2i Shinty' testfile.txt > testfile.tmp.txt
mv testfile.tmp.txt testfile.txt

(I don’t remember if the 2i works on BSDs, I don’t think I tried that and I don’t have a bsd box running right now to check).


Thanks a lot this was very helpful to me, much appreciate your help :slight_smile:

1 Like