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 

marked as duplicate by steeldriver, G-Man, Kusalananda, steve, Jeff Schaller Jan 21 '17 at 11:18

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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 Jan 21 '17 at 6:44
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

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