如何从每个具有匹配文本的文件中删除行?

时间:2013-04-25 04:11:50

标签: linux unix ubuntu grep

$ grep "console.log" * -R
account/db.js:        console.log(err);
account/db.js:        console.log(info);
account/db.js:                console.log(err);
account/db.js:                    console.log(err2);
account/controller.js:    console.log(covers);
account/controller.js:    console.log(req.api_user);
account/controller.js:    console.log(code);
account/controller.js:        console.log(user);
account/helper.js:                console.log(err);
messages/db.js:        console.log("Error " + err);
messages/helper.js:                console.log('No email notify.');
messages/helper.js:                console.log(msg_body);
messages/helper.js:                        console.log(message.sid);
messages/helper.js:                        console.log(message.dateCreated);
messages/helper.js:                        console.log(error);
products/controller.js:            console.log(product);
products/controller.js:                console.log(product);
products/helper.js:        console.log(data)
products/helper.js:    console.log('removing index....');
profile/db.js:                console.log(err);
profile/db.js:                console.log(info);
profile/db.js:                console.log(err);
profile/controller.js:                            console.log("sending phone confirmation text...");
profile/helper.js:            console.log(message.sid);
profile/helper.js:            console.log(message.dateCreated);
profile/helper.js:            console.log(error);
receiver/controller.js:    console.log(from);
receiver/controller.js:    console.log(body);
receiver/controller.js:        console.log(from_email);
receiver/controller.js:        console.log(to_id_gen);
receiver/controller.js:        console.log(finalbody);
receiver/controller.js:                            console.log(result);
reviews/db.js:        console.log(err);
reviews/db.js:        console.log(results);
reviews/controller.js:            console.log(review);
reviews/controller.js:    console.log(review_id);
search/controller.js:        console.log(JSON.stringify(data.hits.hits, null, 4));

正如您所看到的,在我编写代码时,我到处都在使用console.log。

现在,我想删除所有这些行。我不想手动进入每个文件来删除它们。相反,我想通过一个命令来做。

grep "console.log" * -R类似,我怎么能做同样的事情,但递归删除这些行? (从当前目录中查看树中的所有文件)

3 个答案:

答案 0 :(得分:1)

尝试find这样的事情。试试find . -type f -exec sed -i '/console\.log/d' {} \;,但您可能有兴趣使用-i.bak代替-i来保留备份副本

答案 1 :(得分:0)

给这一点。

sed -i.bak '/console.log/d' */*.js

-i param编辑了适当的文件。原始文件的名称会附加.bak,因此如果出现问题您可以将其恢复,或者您改变主意。

这不是一个正确的递归解决方案;您可能需要修改文件名通配符,或从find . -exec ...包装器驱动命令以使其递归。

答案 2 :(得分:0)

Perl:

perl -i -n -e'print unless /console\.log/' $(find . -name '*.js')