1

Wondering the most efficient solution to replace one or more consecutive spaces with one comma? A single command is preferred. :)

I am using Mac OS/Linux.

thanks in advance, Lin

4 Answers 4

2

give this one-liner a try, this will not replace the spaces at the BOL or EOL

awk -v OFS="," '{$1=$1}7' file 

this line will replace all spaces:

awk '1+gsub(/ +/,",")' file 

another one with sed, this will replace all spaces, including leading and ending ones

sed 's/ \+/,/g' file 
Sign up to request clarification or add additional context in comments.

Comments

2

This is what tr provides out of the box

tr -s ' ' ',' 

Comments

1

Using sed:

sed 's/ */,/g' 

As an example:

$ echo 'a b c d' | sed 's/ */,/g' a,b,c,d 

Comments

0

Noting the comment about leading/trailing spaces for this example (and suggesting that OP might not want to convert those):

sed 's/ \+/,/g' file 

and that most people would consider TAB a "space", one could use a more comprehensive (but complicated) approach:

sed \ -e ':loop' \ -e 's/\([^[:space:]]\)[[:space:]][[:space:]]*\([^[:space:]]\)/\1,\2/g' \ -e 't loop' file 

The loop is needed to handle the case where the \1 and \2 overlap.

Here is an example input:

total 36 drwx------ 5 root root 4096 Aug 21 03:58 0994576031 drwx------ 4 tom users 4096 Aug 21 04:27 fake-tom -rw-r--r-- 1 tom users 0 Aug 21 04:53 foo -rw-r--r-- 1 tom users 155 Aug 21 04:27 gpgagent.log drwx------ 2 tom users 4096 Aug 21 04:27 gpg-MOxBtc drwx------ 2 root root 4096 Aug 21 03:58 kde-root drwx------ 2 tom users 4096 Aug 21 04:27 ssh-cdcgKy3228 drwxrwxrwt 2 root root 4096 Aug 21 03:57 VMwareDnD drwxr-xr-x 2 root root 4096 Aug 21 03:58 vmware-root drwx------ 2 root root 4096 Aug 21 03:58 vmware-root-2999462734 

and output

total,36 drwx------,5,root,root,4096,Aug,21,03:58,0994576031 drwx------,4,tom,users,4096,Aug,21,04:27,fake-tom -rw-r--r--,1,tom,users,0,Aug,21,04:53,foo -rw-r--r--,1,tom,users,155,Aug,21,04:27,gpgagent.log drwx------,2,tom,users,4096,Aug,21,04:27,gpg-MOxBtc drwx------,2,root,root,4096,Aug,21,03:58,kde-root drwx------,2,tom,users,4096,Aug,21,04:27,ssh-cdcgKy3228 drwxrwxrwt,2,root,root,4096,Aug,21,03:57,VMwareDnD drwxr-xr-x,2,root,root,4096,Aug,21,03:58,vmware-root drwx------,2,root,root,4096,Aug,21,03:58,vmware-root-2999462734 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.