3

I use the following command to convert my input file contents to lowercase

tr A-Z a-z < input > output 

This command works fine.

But when I try to store the output in input file itself, it is not working. The input file is empty after executing the command. Why?

 tr A-Z a-z < input > input 
jophab
  • 173
  • 4
  • 9

2 Answers2

8

If you have GNU sed you can use

sed -i 's/.*/\L&/' input
  • -i modify file in place
  • s/old/new/ replace old with new
  • .* any characters on each line
  • \L lowercase
  • & the matched pattern
Zanna
  • 3,571
3

But when I try to store the output in input file itself, it is not working. The input file is empty after executing the command. Why?

Because the > input causes the shell to truncate the file before the tr command is run. Incidentially, you can get around this with more advanced descriptor handling in Bash:

exec 8<>input
exec 9<>input
tr '[A-Z]' '[a-z]' <&8 >&9

The exec #<>file opens a file into descriptor # in read-write mode without truncating.

  • 2
    It should be noted that this technique will work reliably only for commands like tr (without the -d or -s option) that write out exactly as much data as they read in, on a one-for-one basis. – G-Man Says 'Reinstate Monica' Jan 21 '17 at 06:44