Linux 如何用sed中的另一个字符替换单引号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17357952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:20:17  来源:igfitidea点击:

How do I replace single quotes with another character in sed?

linuxbashshellunix

提问by Srihari

I have a flat file where I have multiple occurrences of strings that contains single quote, e.g. hari'sand leader's.

我有一个平面文件,其中多次出现包含单引号的字符串,例如hari'sleader's

I want to replace all occurrences of the single quote with space, i.e.

我想用空格替换所有出现的单引号,即

  • all occurences of hari'sto hari s
  • all occurences of leader'sto leader s
  • 出现的所有hari'shari s
  • 出现的所有leader'sleader s

I tried

我试过

sed -e 's/"'"/ /g' myfile.txt

and

sed -e 's/"'"/" "/g' myfile.txt

but they are not giving me the expected result.

但他们没有给我预期的结果。

采纳答案by Antarus

Try to keep sed commands simple as much as possible. Otherwise you'll get confused of what you'd written reading it later.

尽量保持 sed 命令的简单性。否则你会在以后阅读它时对你写的东西感到困惑。

#!/bin/bash
sed "s/'/ /g" myfile.txt

回答by perreal

Just go leave the single quote and put an escaped single quote:

只需离开单引号并放置一个转义的单引号:

sed 's/'\''/ /g' input

also possible with a variable:

也可以使用变量:

quote=\'
sed "s/$quote/ /g" input

回答by n3rV3

This will do what you want to

这将做你想做的事

echo "hari's"| sed 's/\x27/ /g'

It will replace single quotes present anywhere in your file/text. Even if they are used for quoting they will be replaced with spaces. In that case(remove the quotes within a word not at word boundary) you can use the following:

它将替换文件/文本中任何位置的单引号。即使它们用于引用,它们也会被空格替换。在这种情况下(删除不在单词边界的单词内的引号),您可以使用以下内容:

echo "hari's"| sed -re 's/(\<.+)\x27(.+\>)/ /g'

HTH

HTH

回答by Dedy K Wijaya

Here is based on my own experience.

这里是根据我自己的经验。

Please notice on how I use special char 'vs "after sed

请注意我如何使用特殊字符'"之后sed

This won't do (no output)

这不行(没有输出)

2521 #> echo 1'2'3'4'5 | sed 's/'/ /g'
>
>
>

but This would do

但这会做

2520 #> echo 1'2'3'4'5 | sed "s/'/ /g"
12345

回答by Jonni2016aa

The -i should replace it in the file sed -i 's/“/"/g' filename.txt

-i 应该在文件 sed -i 's/“/”/g' filename.txt 中替换它

if you want backups you can do sed -i.bak 's/“/"/g' filename.txt

如果你想要备份你可以做 sed -i.bak 's/“/”/g' filename.txt

回答by Davide Finardi

I had to replace "0x" string with "32'h" and resolved with:

我不得不用“32'h”替换“0x”字符串并解决:

sed 's/ 0x/ 32\x27h/'