Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have two questions about the tr command of Linux shell, ① is :

$ echo 'abcd123' | tr -c 'a-z' '0-9'

the result is : 'abcd9999'. It has 4 '9's,why? And why is 9, not one of '0-8'? ② is :

$ echo hello 1 char 2 next 4 | tr -d -c '0-9 \n'

the result is ; ' 1 2 4 ', can someone explain this for me? how does it execute ?

share|improve this question

migrated from stackoverflow.com Aug 24 '13 at 12:16

This question came from our site for professional and enthusiast programmers.

    
"... of the linux shell" ? /usr/bin/tr is not part of the shell build in commands. It is a separate command. Calling it part of the shell is about the same as calling diablo IV (or any other modern game) part of the windows build in programs. –  Hennes Aug 24 '13 at 12:54

2 Answers 2

up vote 3 down vote accepted

The first question:

echo 'abcd123' actually print 'abcd123\n' to stdout. And for tr -c 'a-z' '0-9' the -c option means complement of 'a-z' will be used for the translation, see man page of tr.

There are many more character excluding 'a-z' correspond to '0-9', so the remaining character of 'abcd123\n', excluding lowercase character, that is '123\n', will be translated to '9999'. So the result is 'abcd9999', with on trailing '\n'.

The second question is much simple:

echo hello 1 char 2 next 4 print hello 1 char 2 next 4\n to stdout. The 'tr -d -c '0-9 \n'' delete every complement of '0-9' number and space character and '\n'.

That is why the remaining character contains numbers and spaces, and by the way a trailing '\n'.

share|improve this answer
    
I have another problem, the command is like this : $ echo 123 | tr -ct '\n' '0', Can you tell me why its result is '123\n'? I thought it may be '023\n' –  user2331313 Aug 24 '13 at 12:11
    
@user2331313 you keep using the -c option, are you sure you want to? Have a look at man tr. –  terdon Aug 24 '13 at 13:53

Regarding the command:

echo 'abcd123' | tr -c 'a-z' '0-9'

The manpage for tr says:

tr [OPTION]... SET1 [SET2]

... SET2 is extended to length of SET1 by repeating its last character as necessary ...

The complement of 'a-z' is all characters except the lowercase letters. So that set is quite a bit longer than the ten characters in '0-9', and the digits in the string "abcd123" match up with the repeated last character, '9'.

In:

echo hello 1 char 2 next 4 | tr -d -c '0-9 \n'

you are effective telling tr to delete anything not in the set of characters you give as SET1. So it deletes all characters except the digits, space and newline. I'm not sure what else you might have been expecting here.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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