Linux 带有文字字符串的 sed——不是输入文件

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

sed with literal string--not input file

linuxunixsed

提问by amphibient

This should be easy: I want to run sedagainst a literal string, not an input file. If you wonder why, it is to, for example edit values stored in variables, not necessarily text data.

这应该很简单:我想针对文字字符串而不是输入文件运行sed。如果你想知道为什么,例如编辑存储在变量中的值,不一定是文本数据。

When I do:

当我做:

sed 's/,/','/g' "A,B,C"

where A,B,C is the literal which I want to change to A','B','C

其中 A,B,C 是我想更改为 A','B','C 的文字

I get

我得到

Can't open A,B,C

As though it thinks A,B,C is a file.

好像它认为 A、B、C 是一个文件。

I tried piping it to echo:

我试着用管道来回声:

echo "A,B,C" | sed 's/,/','/g' 

I get a prompt.

我得到一个提示。

What is the right way to do it?

正确的做法是什么?

采纳答案by Gilles Quenot

You have a single quotes conflict, so use:

你有一个单引号冲突,所以使用:

 echo "A,B,C" | sed "s/,/','/g"

If using bash, you can do too (<<<is a here-string):

如果使用bash,你也可以这样做(<<<是一个here-string):

sed "s/,/','/g" <<< "A,B,C"

but not

但不是

sed "s/,/','/g"  "A,B,C"

because sedexpect file(s) as argument(s)

因为sed期望文件作为参数

EDIT:

编辑

if you use kshor any other ones :

如果您使用ksh或任何其他的:

echo string | sed ...

回答by ferrants

Works like you want:

像你想要的那样工作:

echo "A,B,C" | sed s/,/\',\'/g

回答by phyatt

My version using variables in a bash script:

我的版本在 bash 脚本中使用变量:

Find any backslashes and replace with forward slashes:

找到任何反斜杠并用正斜杠替换:

input="This has a backslash \"

output=$(echo "$input" | sed 's,\,/,g')

echo "$output"