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
    Note [this answer to one of the proposed duplicates in particular](http://unix.stackexchange.com/a/186126/73093), but the answers to this question give an actual solution. – Michael Homer Jan 21 '17 at 06:37

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,491
  • 18
  • 28
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.

DepressedDaniel
  • 4,169
  • 12
  • 15
  • 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