Replacing first occurence in every line

这一生的挚爱 提交于 2019-12-20 04:04:16

问题


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!


回答1:


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

output:

word1, word2 word3



回答2:


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:


how about:

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

output:

word1, word2 word3
word4, word5 word6
word7, word8



回答4:


Using awk

awk '{sub(/ /,", ")}1' file
word1, word2 word3
word4, word5 word6
word7, word8



回答5:


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)




回答6:


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

FRIEND, TOO MUCH



来源:https://stackoverflow.com/questions/20405342/replacing-first-occurence-in-every-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!