1832978 Members
2662 Online
110048 Solutions
New Discussion

Re: sed and tr

 
SOLVED
Go to solution
Gary Yu
Super Advisor

sed and tr

Hi friends,

a quick question, I'm using "tr" to change all capital letters in a file to small letters

cat textfile|tr [:upper:] [:lower:]

but when I try to do the same with "sed"
cat textfile|sed 's/[[:upper:]]/[[:lower:]]/'

it change all capital letters to string "[[:lower:]]", so how can we use sed for that.

PS. why [[:upper:]] in sed instead of [:upper:]

thanks
Gary
7 REPLIES 7
Ted Ellis_2
Honored Contributor
Solution

Re: sed and tr

not very pretty, but straight out of the sed and awk book...

sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'

that should change any caps to its corresponding lowercase...
Ted Ellis_2
Honored Contributor

Re: sed and tr

the y is the sed transform command... so use this instead of s
Rodney Hills
Honored Contributor

Re: sed and tr

tr is geared to do character by character translations. When you use [:upper:] or [:lower:] in sed, that is used in a regular expression only for searching.

If I did
sed -e 's/[123]/a/g'

Then that would replace either 1, 2, or 3 with "a".

Instead of 123 I use character class [:upper:]
sed -e 's/[[:upper:]]/a/g'

that would be the same as-
sed -e 's/[ABCDEFGHIJKLMNOPQRSTUVWXYZ]/a/g'

Which would replace all uppercase characters with "a". So using [[:lower:]] doesn't translate to the equivalent lower case character.

I hope that clarifies your question...

-- Rod Hills
There be dragons...
John Poff
Honored Contributor

Re: sed and tr

Gary,

Yet another reason why Larry Wall wrote Perl:

perl -ne 'print lc()' textfile

Will print your file in all lower case.

JP
Gary Yu
Super Advisor

Re: sed and tr

thanks guys,

Ted's way works(never used 'y' function before).

thanks Rodney for the clarification. BTW, the example sed -e 's/[123]/a/g' , shouldn't it be [1|2|3]

Gary
Rodney Hills
Honored Contributor

Re: sed and tr

No- I think you are thinking of (1|2|3) which is different. [123] is an implied or for all characters in the list. ^ does a logical not, so [^123] would match everything except 1, 2, or 3.

-- Rod Hills
There be dragons...
H.Merijn Brand (procura
Honored Contributor

Re: sed and tr

A side note 1

[:lower:] and friends and perl's uc () and lc () functions also take LOCALE settings into consideration, and are portable to EBCDIC character sets where [a-z] and [A-Z] will fail

As side note 2

probably becoming a peeve pet, but why the h**l do all those examples include the cat command? Is it a hobby to fill the system's process space, or are people still not told enough that unix is based on pipes and redirects are the way to go?

# perl -pe'$_=lc' textfile

will do what you want fast and reliable
Enjoy, Have FUN! H.Merijn