-1
root@calleva:~# echo "f" > file root@calleva:~# f=$(<file) root@calleva:~# echo "$f" f root@calleva:~# echo "$f" | tr -c '[:alpha:]' '_' f_root@calleva:~# echo "$f" | tr -c '[:alpha:]' -d tr: when translating with complemented character classes, string2 must map all characters in the domain to one root@calleva:~# echo "$f" | tr -c '[:alpha:]' '_' | tr -d '_' froot@calleva:~# echo "$f" | sed 's/[^a-z]//g' | tr -c '[:alpha:]' '_' f_root@calleva:~# 

So it appears that tr can do only one of -c and -d and not both at the same time?

And sed simply doesn't work?

4
  • 3
    Your mystery character is a newline, and for me, tr -cd '[:alpha:]' works on FreeBSD. Commented May 9, 2024 at 16:38
  • 1
    ... and sed is line-oriented by default so doesn't consider the newline to be part of the string Commented May 9, 2024 at 16:40
  • 5
    See also: echo ba | tr ab -d. You should quit the habit of using options after non-option arguments. IMO it's a misdesign that some GNU utilities (apparently not tr) accept them. Commented May 9, 2024 at 16:42
  • Control characters are less of a mystery if you pipe them into od -t x1ac, which shows them in hex, ASCII name, and escaped form. Commented May 10, 2024 at 8:28

1 Answer 1

5

The mysterious control character you are trying to remove is a newline character, outputted by echo. This is encoded as \n with tr and would be part of the complement of [:alpha:]. The sed utility won't see it at all as it reads newline-delimited lines.

In your command tr -c '[:alpha:]' -d, you ask to replace the complement of [:alpha:] with -d, and you get an error message saying that the two sets are not of the same length. To use -c and -d at the same time, ensure that options come before operands:

tr -d -c '[:alpha:]' 

Some utilities on Linux systems (often GNU utilities) try to rearrange the given command line arguments so that the order of options in relation to operands is less important to the user, as a convenience feature. The tr utility does not appear to do this, and other utilities on non-Linux systems are likewise less forgiving in this respect. To minimize the number of future surprises, make it a habit to put options before operands.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.