简体   繁体   English

用特殊字符替换字符串

[英]Replace string with special characters

I'm trying to replace the following string in a wordpress sql file: 我正在尝试在wordpress sql文件中替换以下字符串:

http:\\\\/\\\\/firstdomain.com\\\\/qwerty\\\\/wp-content\\\\/uploads\\\\/2018\\\\/07\\\\/section-shape.png

to

https:\\\\/\\\\/seconddomain.com\\\\/wp-content\\\\/uploads\\\\/2019\\\\/06\\\\/section-shape.png

I tried the following command which obviously didn't work 我尝试了以下命令,显然不起作用

sed -i "s#'http:\\\\/\\\\/firstdomain.com\\\\/qwerty\\\\/wp-content\\\\/uploads\\\\/2018\\\\/07\\\\/section-shape.png'#'https:\\\\/\\\\/seconddomain.com\\\\/wp-content\\\\/uploads\\\\/2019\\\\/06\\\\/section-shape.png'#g" database.sql

Someone please help to understand where I missed. 请有人帮助了解我错过的地方。 Thank you very much. 非常感谢你。

You can't seriously apply a sed to a .db file because... well, it's database file not text (most likely sqlite by the way). 您不能认真地将sed应用于.db文件,因为...好吧,它是数据库文件而不是文本(顺便说一下,很有可能是sqlite)。

Instead, you should perform the string replacement with an (UPDATE) SQL query from the SQLite console (or whatever SQL client you have). 相反,您应该使用SQLite控制台(或您拥有的任何SQL客户端)中的(UPDATE)SQL查询执行字符串替换。 Check this link for the replace method in SQLite for example. 例如,在此链接中查找SQLite中的replace方法。

Your first mistake is enclosing your script in double quotes instead of single, thereby inviting the shell to parse its contents before sed gets to see it and thus eating up one layer of backslashes. 您的第一个错误是将脚本用双引号而不是单引号引起来,从而邀请Shell在sed看到它之前先解析其内容,从而占用一层反斜杠。

If you have to deal with single quotes (which you shouldn't given your posted sample input but anyway...) never do this: 如果您必须处理单引号(不应该给您已发布的示例输入,但无论如何...),请不要这样做:

sed "s/foo'bar/stuff/"

do this instead: 改为这样做:

sed 's/foo'\''bar/stuff/'

so the shell isn't interpreting every part of your script. 因此shell不会解释脚本的每个部分。

Beyond that - sed doesn't understand literal strings (see Is it possible to escape regex metacharacters reliably with sed ), so instead just use a tool that does, eg awk: 除此之外-sed不能理解文字字符串(请参阅使用sed是否可以可靠地转义正则表达式元字符 ),因此请使用一个可以执行此操作的工具,例如awk:

awk '
  BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]="" }
  s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+length(old)) }
1' \
  'http:\\/\\/firstdomain.com\\/qwerty\\/wp-content\\/uploads\\/2018\\/07\\/section-shape.png' \
  'https:\\/\\/seconddomain.com\\/wp-content\\/uploads\\/2019\\/06\\/section-shape.png' \
  file
https:\\/\\/seconddomain.com\\/wp-content\\/uploads\\/2019\\/06\\/section-shape.png

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

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