wouldnotliketo
wouldnotliketo

Reputation: 323

sed substitute each character until a pattern occurs

I have an pattern which consists of digits and commas, like this: 123,45,2,14324. There can be any number of digits, and I have no way of knowing how many digits there is between two commas. I need to replace each digit with letter 'k', so 129,54,0,111 becomes kkk,kk,k,kkk. I need to replace it only if a certain pattern occurs before it, and it always appears on a line like this: mypattern:123,421,9,3 pattern_i_don't_need:1499,242,22,1

I need to substitute each digit which directly follows mypattern:, so the example line needs to be changed to:

mypattern:kkk,kkk,k,k pattern_i_don't_need:1499,242,22,1

I can use only sed and/or grep. So far I've learned how to substitute each character on the line in question, like this:

   sed '/^mypattern:/ s/[0-9]/k/g' 

This version finds a line which starts with mypattern: and substitutes each digit on that line. How can I tell sed to 'stop' and not substitute whatever digits occur after spaces and/or letters?

Upvotes: 1

Views: 1655

Answers (2)

grail
grail

Reputation: 930

You could use awk to:

awk '/^mypattern/ && gsub(/[0-9]/,"k",$1)' file

Same concept just awk gives you the option of working on the first column of data separated by white space.

Upvotes: 0

Lars Fischer
Lars Fischer

Reputation: 10229

You can use a sed command like this:

sed -r ':a s/(mypattern:[k,]*)[0-9]/\1k/; t a' yourfile
  • :a is a label that t a jumps to in case s has done a substitution
  • thus you have a "loop":

    while s has replaced one digit with a "k":
        try again to: 
            replace another digit after 
                 "mypattern:" and an optional sequence of "k" and comma:
            with k
    

Upvotes: 3

Related Questions