130

This should be easy: I want to run sed against 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.

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

I get

Can't open A,B,C

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

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?

amphibient
  • 29,770
  • 54
  • 146
  • 240

3 Answers3

184

You have a single quotes conflict, so use:

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

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

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

but not

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

because sed expect file(s) as argument(s)

EDIT:

if you use or any other ones :

echo string | sed ...
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • 2
    strange, doesn't work for me... realizing it's some time ago this was posted, but strange deprecation if that's the problem – superhero Jun 05 '18 at 13:01
13

Works like you want:

echo "A,B,C" | sed s/,/\',\'/g
ferrants
  • 601
  • 6
  • 11
9

My version using variables in a bash script:

Find any backslashes and replace with forward slashes:

input="This has a backslash \\"

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

echo "$output"
phyatt
  • 18,472
  • 5
  • 61
  • 80