简体   繁体   English

sed 同时删除单引号和双引号

[英]sed to remove single and double quotes at the same time

I am trying to remove single quotes and double quotes from a file.我正在尝试从文件中删除单引号和双引号。 Can I do it in a single sed command?我可以在单个 sed 命令中完成吗?

I am trying :我在尝试 :

sed 's/\"//g;s/\'//g' txt file

but get this error但得到这个错误

`' ' is unmatched. '' ' 是无与伦比的。

Please help.请帮忙。

另一种可能性是使用tr

tr -d \'\" file

You cannot escape a single quote inside a pair of singe quotes in shell.您不能在 shell 中的一对单引号内转义单引号。 Escaping double quotes is allowed though.虽然允许转义双引号。 Following sed command should work:以下 sed 命令应该可以工作:

sed "s/['\"]//g" file

试试这个:

sed -e 's|["'\'']||g' txt

要删除单引号,只需对sed的正则表达式使用双引号:

sed -e "s/'//g" ./new_file.csv

You can use commands below您可以使用下面的命令

sed "s/'/ /g" file.txt > newfile.txt
sed 's/\"//g' newfile.txt > Required_file.txt

Required_file.txt is the final output. Required_file.txt是最终输出。

我通过删除周围的引号来解决它(在Centos 7 ),例如:

sed -i s/\'//g file;sed -i s/\"//g file 

Well, here's what I've came to.嗯,这就是我的目的。

First, I found out with ord() what are codes for single and double quotes characters, and then used $(..) syntax to pass it into unquoted sed expression.首先,我使用 ord() 找出了单引号和双引号字符的代码,然后使用 $(..) 语法将其传递给未加引号的 sed 表达式。 I used XX and yy instead of empty strings.我使用 XX 和 yy 而不是空字符串。 Obviously it is faaar from optimal, ie they perhaps should be combined into one expression, I encourage you to experiment with it.显然它不是最优的,即它们可能应该组合成一个表达式,我鼓励您尝试使用它。 There are several techniques to avoid quoting problems, you can also put sed expression into separate file, to avoid it to be interpreted by shell.有几种技术可以避免引用问题,您也可以将 sed 表达式放入单独的文件中,以避免它被 shell 解释。 The ord() / chr() trick is also useful when trying to deal with single unreadable characters in output, eg UTF strings on non-UTF console. ord() / chr() 技巧在尝试处理输出中的单个不可读字符时也很有用,例如非 UTF 控制台上的 UTF 字符串。

dtpwmbp:~ pwadas$ echo '"' | perl -pe 'print ord($_) . "\n";'
34
"
dtpwmbp:~ pwadas$ echo "'" | perl -pe 'print ord($_) . "\n";'
39
'
dtpwmbp:~ pwadas$ echo \'\" 
'"
dtpwmbp:~ pwadas$ echo \'\" | sed -e s/$(perl -e 'print chr(34) . "\n"')/XX/g | sed -e s/$(perl -e 'print chr(39) . "\n"')/yy/g 
yyXX
dtpwmbp:~ pwadas$

EDIT (note that this time, both characters are replaced with the same string "yy").There might be some shell utilities for "translating" characters to character codes and opposite, ie it should be possible to do this without using perl or other language interpreter.编辑(请注意,这一次,两个字符都被替换为相同的字符串“yy”)。可能有一些 shell 实用程序用于将字符“翻译”为字符代码和相反的字符,即应该可以在不使用 perl 或其他语言翻译。

dtpwmbp:~ pwadas$ echo \'\" | sed -e s/[`perl -e 'print chr(34) . chr(39)'`]/yy/g
yyyy
dtpwmbp:~ pwadas$ 

and here's yet another way in shell, perhaps even simpler这是 shell 中的另一种方式,也许更简单

dtpwmbp:~ pwadas$ X="'"; Y='"' ; echo $X$Y; echo $X$Y | sed -e "s/$X/aa/g;s/$Y/bb/g"
'"
aabb
dtpwmbp:~ pwadas$ 

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

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