bashloopssed

Replace text for every nth instance in a line


I wish to replace every 6th instance of a space with a character "+" in a given line :

Now is the Time for All Good Men to Come to the Aid of their Country. How much wood could a wood chuck chuck?

Attempting: sed "s/ /+/6;P;D" text.txt

Which yields:

Now is the Time for All+Good Men to Come to the Aid of their Country. How much wood could a wood chuck chuck?

I desire:

Now is the Time for All+Good Men to Come to the+Aid of their Country. How much+wood could a wood chuck chuck?

I can deal with insert if replace won't work.


Solution

  • Here is a way to do it with a while loop:

    LINE="Now is the Time for All Good Men to Come to the Aid of their Country. How much wood could a wood chuck chuck?"
    
    MAX=$(echo $LINE | grep -o " " | wc -l) # this counts number of spaces in $LINE
    
    COUNTER=6
    while [ $COUNTER -lt $MAX ]; do 
      LINE=$(echo $LINE | sed "s/ /+/${COUNTER};P;D")
      COUNTER=$(echo $(($COUNTER + 5)) )
    done
    
    echo $LINE
    #Now is the Time for All+Good Men to Come to the+Aid of their Country. How much+wood could a wood chuck chuck?
    

    In the while loop, I use $COUNTER + 5 (not + 6) because we have to consider the space that has already changed to a "+" from the previous iteration (thus it is substituting the space at every 6-minus-1 instance).