Insert multiple lines of data onto a file after pattern matches using Linux shell script

Updated on September 1, 2017

Have a piece of code that has to be inserted in multiple files? Then, you are just like me having a tough time! I was working on a website hosted in cpanel which had numerous HTML files to each of which a popup code had to be inserted. The number of HTML files were 425. It was a nightmare doing it in windows. But hey, didn’t I tell you I found a smarter way of doing it. Checkout below!

Step 1: Copy files from CPANEL

Copy all the files from cpanel to your local windows system using WinSCP.

Step 2: Copy files from Windows to Linux

Then copy the HTML files to a Linux Server. If you don’t have a server of your own, then you can run a Linux system virtually on your desktop using virtualbox. Checkout how to install virtualbox here.

Linux Shell Scripting tutorial

Step 3: Use ‘sed’ command to insert code

Use the below sed command, to insert your code from an another file. For example: Data to be inserted from “add.txt” file into “input.txt”. Now the command would be :

Input.txt

abcd
efgh
ijkl
mnop
qrst

add.txt

uvwx
yzab
cdef
ghij
klmn
$sed '/ijkl/r add.txt' input.txt

The command would add the content from add.txt to input.txt after the pattern “ijkl” matches. So the output would be:

abcd
efgh
ijkl
uvwx
yzab
cdef
ghij
klmn
mnop
qrst

The above command would output the content on the terminal. To update the file with the contents, then use the “-i” with sed command as shown below:

$sed -i '/ijkl/r add.txt' input.txt

If you have to insert content directly inputing and not from the file, then you can use the below command:

$sed -i 's/.*ijkl.*/uvwx\n&/' input.txt
abcd
efgh
ijkl
uvwx
mnop
qrst

Step 4: Run the above command in a loop with the number of files

Goto the directory where files need to be modified. Use “for loop” insert the data with the below command:

for i in *;
do
    $sed '/ijkl/r add.txt' $i
done

In the above code * represents the files. For each file, as $i, add the contents from add.txt file after the pattern “ijkl” is matched.

Step 5: Copy back the files from Linux to windows to Cpanel

The final step is to copy back the edited files from the Linux server to the local windows system. And then use scp or ftp to copy files from local windows system to cpanel.

Was this article helpful?

Related Articles

Leave a Comment