Reputation: 10139
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
Upvotes: 1
Views: 125
Reputation: 54505
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
Upvotes: 0
Reputation: 113824
Using sed:
sed 's/ */,/g'
As an example:
$ echo 'a b c d' | sed 's/ */,/g'
a,b,c,d
Upvotes: 1
Reputation: 195039
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
Upvotes: 2