简体   繁体   English

如何使用bash在Linux上删除多个文件中的多行

[英]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. 我正在尝试从Linux共享主机上的所有Javascript文件中删除2行。 I wanted to do this without writing a script as I know this should be possible with sed . 我想这样做而无需编写脚本,因为我知道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. 如您所料,我的服务器已被黑客入侵,因此我需要清理所有这些JavaScript文件。

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 ; VAR

O0l='=sTKpUG O0l ='= sTKpUG

except that the second line is longer, but the rest of the second line should not influence the command. 除了第二行更长,但第二行的其余部分不应影响该命令。

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. 由于sed逐行处理输入文件,因此它不会在其缓冲区中存储换行符'\\ n',因此我们需要使用标志/ N来告知它以换行符附加下一行。

/^;var/N;

Then we do our pattern searching and deleting. 然后,我们进行模式搜索和删除。

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

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. 目前还不清楚这两行是什么样子,也不清楚它们在JavaScript中是否彼此相邻,因此我们假设不是。 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; 还有其他方法可以使用单个命令字符串编写sed脚本。 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. 显然,如果您需要在其中一行中保留一些信息,则可以使用适当调整的搜索模式,然后使用替代s/short-pattern//代替d来删除必须除去。 Similarly with the long line if that's relevant. 如果需要的话,与长线相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM