简体   繁体   中英

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.

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.

What is the best way to do that in sed?

I tried this: 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. 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.

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.*",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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