简体   繁体   English

如何正确使用SED更改文件中的行?

[英]How to change a line in a file using SED properly?

I'm trying to use bash's SED command in OS X and failing. 我试图在OS X中使用bash的SED命令,但失败了。

I need to change this line #"phpunit/phpunit:3.7.*", to the same but without the # (so like this "phpunit/phpunit:3.7.*", in my file. 我需要将此行#"phpunit/phpunit:3.7.*",更改为同一行,但不包含# (因此在我的文件"phpunit/phpunit:3.7.*",

What is the best way to do that in sed? 在sed中执行此操作的最佳方法是什么?

I tried this: sed -i -e "s/#\\"phpunit/phpunit:3.7.*\\",/\\"phpunit/phpunit:3.7.*\\"," file.txt 我试过了: sed -i -e "s/#\\"phpunit/phpunit:3.7.*\\",/\\"phpunit/phpunit:3.7.*\\"," file.txt

but that didn't work :( 但这没有用:(

I can see an obvious error, that you use the substitution separator character (the slash) inside the regular expression part. 我可以看到一个明显的错误,即您在正则表达式部分中使用了替换分隔符(斜杠)。 You must escape it, like: 您必须将其转义,例如:

sed -e "s/#\"phpunit\/phpunit:3.7.*\",/\"phpunit\/phpunit:3.7.*\",/" file.txt

An improvement could be to group what you want to keep, like: 可以将您想保留的内容归为一组,例如:

sed -e "s/#\(\"phpunit\/phpunit:3.7.*\",\)/\1/" file.txt

Both solutions yield: 两种解决方案都可以:

"phpunit/phpunit:3.7.*",

I don't use OS X , so I omitted the -i switch. 我不使用OS X ,所以省略了-i开关。 In linux is enought -i with an space following it, but in your system I think you must provide a blank string, like: -i'' but not sure, so test this part. linux-i后面有一个空格是足够的,但是在您的系统中,我认为您必须提供一个空白字符串,例如: -i''但不确定,因此请测试这一部分。

Why not just use something like 为什么不只使用类似

sed 's/#//' file.txt

And if you need more specificty then 如果您需要更多的特异性,

sed 's/#"php/"php/' file.txt
$ cat input
#"phpunit/phpunit:3.7.*",

Some serious back-slashing later, due to the special characters * , . 由于特殊字符* ,,稍后会出现严重的反斜杠. and / : /

$ sed  's/#"phpunit\/phpunit:3\.7\.\*",/"phpunit\/phpunit:3\.7\.\*",/' input
"phpunit/phpunit:3.7.*",

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

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