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


  • sed 's/[[:blank:]]\+/,/g' – mug896 Dec 25 '15 at 12:55

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'.

  • 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. – aneuryzm 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.

awk '{print $1","}' Servers | tr -d '[\n]' | xargs echo 

Here the file name is Servers.. It contains the below content..


If we use the above command we can get the below output..


[mohramak@oc3246038448 Desktop]$ cat Servers
[mohramak@oc3246038448 Desktop]$ awk '{print $1","}' Servers | tr -d '[\n]' | xargs echo 
[mohramak@oc3246038448 Desktop]$ 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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