Linux is an awesome operating system, without a doubt. It becomes more useful with it’s in-built powerful tools. For instance today we are going to see how powerful utility Stream Editor “sed” is!

Imagine you are in a situation when you want to change certain text string in say 10,000 files, what are you going to do? I have seen people download those 10,000 files and then open bunch of them in an editor and do “find all” / “replace all”. Well, that’s good if you have enough time to kill and you are very patient by nature.

However, smart users just won’t do that and instead use this powerful utility called “sed” to replace string in as many files. Let’s see how is it done by taking an example of a website where some malicious code is injected inside each and every file.

In the first example, we will use  sed to replace malicious code from all php files within same directory level.

#command syntax
sed -i 's/oldstring/newstring/g' *.txt
#acutal command
sed -i 's/eval(base64_decode("dnajkdbasjdbasjdasbjnkldnakdnasknklnKNDAKLSNDSALKNDKLASn"));//g' *.php

Every file in the directory that has the malicious code, will be removed since we have put nothing in the replacement part of the command. Here’s how the switches work –

  • i switch – is responsible for the inline insertion.
  • g switch – globally,remove occurrences in the given file.

 But what if you have this code injected all over directories? Have a look at the following example which finds all the php files in the subdirectories and removes the malicious code.

find ./ -type f -exec sed -i 's|eval(base64_decode("dnajkdbasjdbasjdasbjnkldnakdnasknklnKNDAKLSNDSALKNDKLASn"));||g' *.php {} \;

Notice that in the above command, I have used a different separator but it does not really matter.  find  command is responsible for the recursive nature and exec will execute our sed command as required.

Hope this helps you and you should be able to save some time.

Stay Digified!!
Sachin Khosla

Share this post: