Search code examples
sedregexp-replace

Use sed to replace every character by itself followed by $n times a char?


I'm trying to run the command below to replace every char in DECEMBER by itself followed by $n question marks. I tried both escaping {$n} like so {$n} and leaving it as is. Yet my output just keeps being D?{$n}E?{$n}... Is it just not possible to do this with a sed?

How should i got about this.

echo 'DECEMBER' > a.txt
sed -i "s%\(.\)%\1\(?\){$n}%g" a.txt
cat a.txt

Solution

  • Range (also, interval or limiting quantifiers), like {3} / {3,} / {3,6}, are part of regex, and not replacement patterns.

    You can use

    sed -i "s/./&$(for i in {1..7}; do echo -n '?'; done)/g" a.txt
    

    See the online demo:

    #!/bin/bash
    sed "s/./&$(for i in {1..7}; do echo -n '?'; done)/g" <<< "DECEMBER"
    # => D???????E???????C???????E???????M???????B???????E???????R???????
    

    Here, . matches any char, and & in the replacement pattern puts it back and $(for i in {1..7}; do echo -n '?'; done) adds seven question marks right after it.