tr

No results when using -c option in tr command


No translation occurs when using -c option in tr command in linux.
For example tr -c "[:digit:]" "#" or tr -c [:digit:] "#". When I type text like abc instaed of ###, nothing happens.
Input: qwe123ty12.
Expected output: ###123##12#
Current output: ###123##12##


Solution

  • When you hit Enter, that's a character, too: Newline (sometimes written as \n).

    Your character class includes all non-digit characters, including newline. That's why every time you hit Enter, another # is added to the output. It's not immediately visible because output is only flushed when a newline is printed (which never happens with your set of options) or when the end of the input is reached (which is Ctrl+D for interactive input).

    You can exempt newline from being turned into # by doing

    tr -c '[:digit:]\n' '#'
    

    This adds \n to the set of characters to be left alone.