Marcus Burkhart
Marcus Burkhart

Reputation: 29

Bash replace a comma with space colon space sequence

I want to replace all commas in my file with a space, colon and space. I keep getting the error "Only one string may be given when deleting without squeezing repeats". Here is my command, where am I going wrong?

tr -d "," " : " < testfile

Upvotes: 1

Views: 6770

Answers (3)

paxdiablo
paxdiablo

Reputation: 882786

tr -d is usually used for deleting characters. If you want a quick way to replace commas with a space-colon-space sequence1, just use:

sed 's/,/ : /g' testfile

Once you're happy with the output, you can used sed -i to replace the original file, if that's what you want:

sed -i.bak 's/,/ : /g' testfile

That will modify the file, leaving the original contents in testfile.bak. If your sed isn't advanced enough to have the -i option, you can do it manually:

mv testfile testfile.bak
sed 's/,/ : /g' testfile.bak >testfile

1 If you're just trying to replace commas with colons (with no surrounding spaces), you can still use tr:

tr ',' ':' <testfile

or using the same -i-emulation as for less advanced sed implementations if you want to modify the original file:

mv testfile testfile.bak
tr ',' ':' <testfile.bak >testfile

Upvotes: 4

Russ Huguley
Russ Huguley

Reputation: 866

just take out the -d and your command works. You probably just want to take the spaces from around your colon. It will take sequences of both sets and replace them. so your replacing your comma with a space with what you have.

Upvotes: 0

zzevannn
zzevannn

Reputation: 3734

If I'm deciphering what you're looking for correctly, sed is probably a better tool for this. tr does substitution, but only for single characters. If multiple characters are given it expects them to be a list of find and replacements, e.g.:

$ echo "hi"| tr "ih" "on"
no

It replaces i with o and h with n to make hi into no.

You're also using the -d switch, which is to delete characters.

To use sed though, you'd want something like this:

sed 's/,/ : /g' input > output

Depending on the version of sed used you may be able to use the -i switch to act on the file in place and avoid the redirect and new file.

sed is a stream editor that reads by lines, so this will go line by line through the file and replace each comma with a colon surrounded by spaced.

sed is very powerful and you should read up on it if you want to use it more, but the simple syntax used here is 's/regex/replacement/g' with the g at the end meaning global, or replace all.

Upvotes: 0

Related Questions