regexlinuxterminalcsh

how replace string repeated pattern at his start ,linux terminal?


I want to edit a string that I get using regular expression in linux shell but I failed.

the thing I want to do is at the start of the string to change repeatedlly occurrence of "00" to "1"

let say : 00000120001 to 110100001 but I failed to that.

I tried:

echo 00000120001 | sed 's/^\`\<00/1/g' 

but got 1000120001


Solution

  • Not sure you can do it with a single regex; I have a solution with juggling with the hold and pattern spaces of sed.

    In one line:

    sed 'h;s/[^0].*//;s/00/1/g;x;s/^0*//;x;G;s/\n//' <<< '00000120001'
    

    With details:

    sed 'h          # copy input line to hold space
         s/[^0].*// # keep only 00..0 prefix in pattern space
         s/00/1/g   # replace double 0s by 1s in pattern space
         x          # swap hold and pattern spaces (hold is now 110, pattern 00000120001
         s/^0*//    # remove 00..0 prefix from pattern space
         x          # swap hold and pattern spaces (hold is now 120001, pattern 110
         G          # append hold space to pattern space (pattern is 110\n120001)
         s/\n//'    # remove \n from pattern
    <<< '00000120001'