I'm trying to delete every character except a-z and A-Z from a file, so I'm piping this command after cat file.txt. (cat file.txt | tr -d [^a-zA-Z]) , but for some reason it doesn't work.
tr -d [^a-zA-Z]
Thanks
I'm trying to delete every character except a-z and A-Z from a file, so I'm piping this command after cat file.txt. (cat file.txt | tr -d [^a-zA-Z]) , but for some reason it doesn't work.
tr -d [^a-zA-Z]
Thanks
To complement a set, use -c
:
tr -c -d 'a-zA-Z'
but you might prefer:
tr -d -c '[:alpha:]'
The argument to tr
is not a regular expression at all, and the command tr -c '[^a-zA-z]'
will simply delete all characters that are ^
, [
, ]
, or in the set a-z
or A-Z
. That is, adding ^
to the set does not complement the set (or act as an anchor to the start of a line as it would in a regex), it just adds ^
to the set of characters to match.
Without quotes, things get weirder, and the shell will (or not, depending on some shell settings) first expand tr [^a-zA-Z]
with a glob and potentially invoke tr
with multiple arguments. Any single letter filename will match, so if there is exactly one such file in the current working directory then any character in the stream that matches that name will be deleted, but if there is more than one such name in the current working directory tr
will throw an error and abort. If there are no such names, the command will execute the same as if quotes were present.