dan
dan

Reputation: 203

sed or awk remove (,) from text file

here the scenarios I have. the text file looks like this

"1","2,c","3","4,a","7"
"8","9,c","4","6,d","9"

so what I want is replace (,) with (-)

ex - instead of "2,c" to be "2-c" I only need the comma inside "" to be change not other comma separated used for csv file. this should change globally

Thanks!!

Upvotes: 1

Views: 733

Answers (2)

Astronomyde
Astronomyde

Reputation: 65

I have done alot of global replaces and have an alternative,you might just be making life too complicated here. If you use the emacs editor you can just do three global replace statements:

M-x repl-s "," "--" replace the "," with a unique string, then just
M-x repl-s ' where you replace all remaining ' with a space, then you just put the other comma's back with

M-x repl-s "--" "," I know this isn't strictly a sed example but I thought it might provide a nice alternative. I sometimes prefer to just hop in a text editor rather than sed-ing everything up, but that might just be me.

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 224982

s#([^"]),([^"])#\1-\2#g works on your example:

$ cat example 
"1","2,c","3","4,a","7"
"8","9,c","4","6,d","9"
$ sed -E -e 's#([^"]),([^"])#\1-\2#g' example
"1","2-c","3","4-a","7"
"8","9-c","4","6-d","9"

The sed expression breaks down as "replace all , characters that aren't between two " characters with - characters".

Edit: OP's sed doesn't support extended (modern) regular expressions, so here's an example with a BRE:

$ sed -e 's#\([^"]\),\([^"]\)#\1-\2#g' example
"1","2-c","3","4-a","7"
"8","9-c","4","6-d","9"

Upvotes: 4

Related Questions