Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I need to replace all white spaces inside my text with commas. I'm currently using this line but it doesn't work: I get as output a text file which is exactly the same of the original one:

sed 's/[:blank:]+/,/g' orig.txt > modified.txt


share|improve this question

2 Answers 2

up vote 5 down vote accepted

With sed:

sed -e 's/\s\+/,/g' orig.txt > modified.txt

Or with perl:

perl -pne 's/\s+/,/g' < orig.txt > modified.txt

Edit: To exclude newlines in perl you could use a double negative 's/[^\S\n]+/,/g' or match against just the white space characters of your choice 's/[ \t\r\f]+/,/g'.

share|improve this answer
Thanks, however there is still an issue: I don't want to replace "next lines \n" with a comma, and the command with perl is currently doing it. She sed command you wrote, it still doesn't work. –  Patrick Apr 22 '11 at 8:29
Sorry you need to escape the + operator in sed, I just updated my answer. Newlines are whitepsace in perl, so you will have to do your whitepsace class manually if you don't wnat to include it. I added two solutions for that as wel. –  Caleb Apr 22 '11 at 8:41

Using tr:

tr -s '[:blank:]' ',' <file

This will replace any horizontal whitespace with a comma. Any repeated whitespace will only be replaced with a single comma.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.