Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed with literal string--not input file

Tags:

linux

unix

sed

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?

like image 238
amphibient Avatar asked Oct 24 '12 18:10

amphibient


People also ask

Can you use sed on a string?

The sed command is a common Linux command-line text processing utility. It's pretty convenient to process text files using this command. However, sometimes, the text we want the sed command to process is not in a file. Instead, it can be a literal string or saved in a shell variable.

Does sed write to file?

Sed provides “w” command to write the pattern space data to a new file. Sed creates or truncates the given filename before reads the first input line and it writes all the matches to a file without closing and re-opening the file.

Does sed change the original file?

By default sed does not overwrite the original file; it writes to stdout (hence the result can be redirected using the shell operator > as you showed).


2 Answers

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):

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 ksh or any other ones :

echo string | sed ... 
like image 169
Gilles Quenot Avatar answered Oct 05 '22 21:10

Gilles Quenot


Works like you want:

echo "A,B,C" | sed s/,/\',\'/g 
like image 26
ferrants Avatar answered Oct 05 '22 21:10

ferrants