Sunday, May 11, 2008

How to convert text files to all upper or lower case

How can you convert a text file to all lower case or all upper case?

As usual, in Linux, there are more than 1 way to accomplish a task.

To convert a file (input.txt) to all lower case (output.txt), choose any ONE of the following:

  • dd
    $ dd if=input.txt of=output.txt conv=lcase

  • tr
    $ tr '[:upper:]' '[:lower:]' < input.txt > output.txt

  • awk
    $ awk '{ print tolower($0) }' input.txt > output.txt

  • perl
    $ perl -pe '$_= lc($_)' input.txt > output.txt

  • sed
    $ sed -e 's/\(.*\)/\L\1/' input.txt > output.txt

    We use the backreference \1 to refer to the entire line and the \L to convert to lower case.


To convert a file (input.txt) to all upper case (output.txt):

  • dd
    $ dd if=input.txt of=output.txt conv=ucase

  • tr
    $ tr '[:lower:]' '[:upper:]' < input.txt > output.txt

  • awk
    $ awk '{ print toupper($0) }' input.txt > output.txt

  • perl
    $ perl -pe '$_= uc($_)' input.txt > output.txt

  • sed
    $ sed -e 's/\(.*\)/\U\1/' input.txt > output.txt


12 comments:

  1. nice :-) . may come in handy. thanx.

    ReplyDelete
  2. thanks, always great to learn about sed ;)

    The dd one surprised me, but that's linux ! Always surprising !

    ReplyDelete
  3. when converting accented vowels

    some conversions fail but this one work

    sed -e's/.*/\L&/'

    ReplyDelete
  4. There's always something more to learn about sed. Thanks!

    ReplyDelete
  5. Awesome!!!!
    tr function is great...:)

    ReplyDelete
  6. can we use cat command to convert text???

    ReplyDelete
  7. good article

    it could be more easy with

    #tr "a-z" "A-Z" < input.file

    ReplyDelete
  8. There are some examples over here as well: http://www.digitalinternals.com/script/shell-script-convert-uppercase-lowercase/414/

    ReplyDelete
  9. BASH SCRIPT WITH EMBEDDED PERL SCRIPT

    #!/bin/bash

    perl -i.bak -e '
    while(<>) {
    print "\L$_";
    }
    ' $*

    ReplyDelete
  10. #!/bin/bash

    perl -i.bak -e '
    while(<>) {
    print "\L$_";
    }
    ' $*

    ReplyDelete