Gary Schermer
Gary Schermer

Reputation: 13

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.

Upvotes: 1

Views: 318

Answers (3)

potong
potong

Reputation: 58578

This might work for you (GNU sed):

sed -E ':a;ta;s/ /+\n/6;H;tb;z;x;s/\n//gp;d;:b;x;s/(.*)\n.*/\1/;x;D' file

This solution replaces every 6th space by +\n and appends the result to the hold space.

When the first substitution fails, the hold space is recalled and printed after first removing any newline artefacts introduced.

N.B. This solution strictly observes the OP specification "replace every 6th instance of a space with a character "+" in a given line" but may easily altered to obey a set of spaces rather than one,using:

sed -E ':a;ta;s/ +/+\n/6;H;tb;z;x;s/\n//gp;d;:b;x;s/(.*)\n.*/\1/;x;D' file

Also note the idiom :a;ta which resets the substitution internal success switch, which is necessary since the D command may leave the switch on.

Upvotes: 0

LC-datascientist
LC-datascientist

Reputation: 2106

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).

Upvotes: 0

Cyrus
Cyrus

Reputation: 88999

With GNU sed:

Insert \n after + and append to your command | tr -d '\n'.

Upvotes: 1

Related Questions