简体   繁体   English

用于替换“with”的UNIX Sed命令

[英]UNIX Sed Command to Replace ` with '

My file test.csv contain Record `Ashish` . 我的文件test.csv包含`Ashish` I want to globally replace it with single quote 'Ashish' . 我想在全球范围内用单引号'Ashish'替换它。

I tried this command: 我试过这个命令:

sed 's/`/'/g' test.csv 

but it is not working. 但它不起作用。 Please advise. 请指教。

tr是替换字符的正确工具:

echo '`' | tr \` \'

Try using double quotes " on the outside and escaping the backtic. 尝试使用双引号"在外面和逃避backtic。

sed "s/\`/'/g" Test.in > Test.out

Also, if you want to change the original file, you have to use the -i flag. 此外,如果要更改原始文件,则必须使用-i标志。

sed -i "s/\`/'/g" Test.in 

你需要转义'`字符:

sed s/\'/\`/g test.csv > out.csv

The reason that fails is because it is not possible to place a single quote in a single quoted string: https://www.gnu.org/software/bash/manual/bashref.html#Single-Quotes 失败的原因是因为无法在单个带引号的字符串中放置单引号: https//www.gnu.org/software/bash/manual/bashref.html#Single-Quotes

The workaround is this: 解决方法是这样的:

  • sed 's/`/'"'"'/g'
    • concatenate a single-quoted string ( 's/`/' ) with a double-quoted string ( "'" ) and another single-quoted string ( '/g' ), or 将单引号字符串( 's/`/' )与双引号字符串( "'" )和另一个单引号字符串( '/g' )连接在一起,或者
  • sed 's/`/'\\''/g'
    • concatenate a single-quoted string with a literal single quote and another single-quoted string, or 将单引号字符串与文字单引号和另一个单引号字符串连接起来,或者
  • other quoting strategies given in other answers 其他答案中给出的其他引用策略

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

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