2

Supposing I have a document formatted like this:

word1 word2 word3
word4 word5 word6
word7 word8

How do I use sed to replace the first occurence of space with a comma followed by a space so that the document will look like:

word1, word2 word3
word4, word5 word6
word7, word8

Thank you!

0

6 Answers 6

7

Simple:

sed -i 's/ /, /' your_file

This looks for the first occurrence of a space, replaces it with a comma and space, then moves to the next line.

3
echo word1 word2 word3|sed -r 's/(\s)/,\1/'

output:

word1, word2 word3
2
  • what about line with at only space Commented Dec 5, 2013 at 21:11
  • 2
    if you have such lines, place /^\s+$/! on top.
    – Endoro
    Commented Dec 5, 2013 at 21:33
2

how about:

sed -e 's/\s\+/, /'

output:

word1, word2 word3
word4, word5 word6
word7, word8
1
  • 2
    This would replace one or more spaces with a , followed by a space.
    – potong
    Commented Dec 5, 2013 at 20:56
2

Using awk

awk '{sub(/ /,", ")}1' file
word1, word2 word3
word4, word5 word6
word7, word8
1
  • This should be the accepted answer. It isn't regex-dependent yet effective!
    – Nikolas
    Commented Apr 9, 2021 at 4:43
1
sed 's/\([^[:blank:]]\{1,\}\)/\1,/' YourFile

Add a , after first block of "non space", so start of line could be starting with space, it still work and also if line is without work but only with space (no , in this case)

0

echo FRIEND TOO MUCH |sed 's/ /, /'

FRIEND, TOO MUCH

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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