bash 如何使用 sed 用 \(space) 替换空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41662400/
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-09-18 15:37:13  来源:igfitidea点击:

How to replace space with \(space) using sed?

bashshellsed

提问by Somenath Sinha

When I use sed to replace all the spaces with X, the command works, the command being:

当我使用 sed 用 X 替换所有空格时,命令有效,命令为:

sed 's/ /X/g' filelist.tmp

However, when I try the same to replace all occurrences of space with \space, the code being :

但是,当我尝试用 \space 替换所有出现的空格时,代码为:

sed 's/ /\ /g' filelist.tmp

It doesn't work. What am I doing wrong? Note that I'm new to shell scripting.

它不起作用。我究竟做错了什么?请注意,我是 shell 脚本的新手。

回答by heemayl

Add another \i.e. you need to make \literal:

添加另一个\即你需要使\文字:

sed 's/ /\ /g'

With only a single \before space, the \is escaping the following space; as the space is not a special character in replacement that needs escaping, it is being taken as is.

\前面只有一个空格, the\正在转义后面的空格;由于空格不是需要转义的替换中的特殊字符,因此按原样使用。

Example:

例子:

% sed 's/ /\ /g' <<<'foo  bar  spam'
foo\ \ bar\ \ spam

回答by Daniel

You should use -r argument and should fix syntax to

您应该使用 -r 参数并且应该将语法修复为

sed -r "s/\s/\\s/g" filelist.tmp

You have mistake in order of escaping "\" also.

您在转义“\”的顺序上也有错误。