Vincent
Vincent

Reputation: 37

How to remove multiple lines in multiple files on Linux using bash

I am trying to remove 2 lines from all my Javascript files on my Linux shared hosting. I wanted to do this without writing a script as I know this should be possible with sed. My current attempt looks like this:

find . -name "*.js" | xargs sed -i ";var 
O0l='=sTKpUG"

The second line is actually longer than this but is malicious code so I have not included it here. As you guessed my server has been hacked so I need to clean up all these JavaScript files.

I forgot to mention that the output I am getting at the moment is:

sed: -e expression #1, char 4: expected newer version of sed

The 2 lines are just as follows consecutively:

;var

O0l='=sTKpUG

except that the second line is longer, but the rest of the second line should not influence the command.

Upvotes: 1

Views: 3324

Answers (2)

JiuDong
JiuDong

Reputation: 130

He meant removing two adjacent lines.

you can do something like this, remember to backup your files.

find . -name "*.js" | xargs sed  -i -e "/^;var/N;/^;var\nO0l='=sTKpUG/d"

Since sed processes input file line by line, it does not store the newline '\n' character in its buffer, so we need to tell it by using flag /N to append the next line, with newline character.

/^;var/N;

Then we do our pattern searching and deleting.

/^;var\nO0l='=sTKpUG/d

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 753890

It really isn't clear yet what the two lines look like, and it isn't clear if they are adjacent to each other in the JavaScript, so we'll assume not. However, the answer is likely to be:

find . -name "*.js" |
xargs sed -i -e '/^distinctive-pattern1$/d' -e '/^alternative-pattern-2a$/d'

There are other ways of writing the sed script using a single command string; I prefer to use separate arguments for separate operations (it makes the script clearer).

Clearly, if you need to keep some of the information on one of the lines, you can use a search pattern adjusted as appropriate, and then do a substitute s/short-pattern// instead of d to remove the short section that must be removed. Similarly with the long line if that's relevant.

Upvotes: 0

Related Questions