shell

How add character after every first number in every line using sed?


I am trying to add ," after every first number of every line

input.txt

1 In the beginning, God created the heavens and the earth. 
2 The earth was without form and void, and darkness was over the face of the deep. And the Spirit of God was hovering over the face of the waters. 
3 And God said, “Let there be light,” and there was light. 
4 And God saw that the light was good. And God separated the light from the darkness. 
5 God called the light Day, and the darkness he called Night. And there was evening and there was morning, the first day. 
6 And God said, “Let there be an expanse in the midst of the waters, and let it separate the waters from the waters.” 
7 And God made the expanse and separated the waters that were under the expanse from the waters that were above the expanse. And it was so. 
8 And God called the expanse Heaven. And there was evening and there was morning, the second day. 
9 And God said, “Let the waters under the heavens be gathered together into one place, and let the dry land appear.” And it was so. 
10 God called the dry land Earth, and the waters that were gathered together he called Seas. And God saw that it was good. 

Output I want to generate is shown below

1,"In the beginning, God created the heavens and the earth. 
2,"The earth was without form and void, and darkness was over the face of the deep. And the Spirit of God was hovering over the face of the waters. 
3,"And God said, “Let there be light,” and there was light. 
4,"And God saw that the light was good. And God separated the light from the darkness. 
5,"God called the light Day, and the darkness he called Night. And there was evening and there was morning, the first day. 
6,"And God said, “Let there be an expanse in the midst of the waters, and let it separate the waters from the waters.” 
7,"And God made the expanse and separated the waters that were under the expanse from the waters that were above the expanse. And it was so. 
8,"And God called the expanse Heaven. And there was evening and there was morning, the second day. 
9,"And God said, “Let the waters under the heavens be gathered together into one place, and let the dry land appear.” And it was so. 
10,"God called the dry land Earth, and the waters that were gathered together he called Seas. And God saw that it was good. 

Below is my MWE

#!/bin/bash

cat input.txt|sed 's/ /,"/'

Solution

  • What I would do:

    sed -E 's/^[0-9]+/&,"/' file
    

    The regular expression matches as follows:

    Node Explanation
    ^ the beginning of the string anchor
    [0-9]+ any character of: '0' to '9' (1 or more times (matching the most amount possible))

    In the remplacement part, & is what matched in the left part