7

I'm trying to take all occurrences of # and if they are consecutive replace them with just one #.

e.g.

 ab ### cde fghi## jklm

would become:

ab # cde, fghi# jklm

My initial goal was to replace all consecutive digits with # so; 120 -> # and 3->#. However I found that 120->###. So now I'm left with this new problem.

21

Using tr -s:

$ echo 'ab ### cde fghi## jklm' | tr -s '#'
ab # cde fghi# jklm

-s Squeeze multiple occurrences of the characters listed in the last operand (either string1 or string2) in the input into a single instance of the character. This occurs after all deletion and translation is completed.


Your original problem could have been solved with:

sed -E 's/[0-9]+/#/g'

Or POSIXly:

sed 's/[[:digit:]]\{1,\}/#/g'

Or:

tr -s '[:digit:]' '[#*]'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.