How to insert string into a file, even multiple files

Stanley Meng
1 min readOct 31, 2019

--

Say, you got several lines of codes. Now, you want to insert them into bunch of files. Put your codes into a file.

/*Filename: input.txt*/
/*below is your code, yes, I know, it's ugly*/
>>I'm here<<

Now, you got bunch of files to deal with, which are all in , say, ./tmp/ folder, and with file extension .txt. You want to insert the code above into all the .txt file.

I assume all these ./tmp/*.txt files have some kind of patterns in them. For instance, one txt file looks like this:

# step 1
abc
efd
# step 2
abc
efd

OK. Now, I want to insert my code (in input.txt) into the ./tmp/*.txt files, just right behind the pattern “step 1”.

Try this command:

find ./tmp    -name "*txt" -exec sed -i -E '/# step 1$/r input3.txt' {}  +

As a result, you’ll get

$ cat ./tmp/test.txt                                                                                                          
# step 1
>>I'm here<<
abc
efd
# step 2
abc
efd

--

--

No responses yet