Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing first occurence in every line

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!

like image 730
Casteurr Avatar asked Jan 28 '26 02:01

Casteurr


2 Answers

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.

like image 178
Manny D Avatar answered Jan 29 '26 22:01

Manny D


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

output:

word1, word2 word3
like image 32
Endoro Avatar answered Jan 29 '26 22:01

Endoro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!