0

I am trying to modify all the files in a directory by changing all the lowercase characters to uppercase characters with this script:

#!/usr/bin/env bash
for file in "/home/user/*"
do
   tr '[:lower:]' '[:upper:]' < "$file" > "$file"
done

But with that script, all the content in the files is erased and I don't understand why.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
JesusR
  • 9
  • 1

2 Answers2

0

You can't use the same file as both input and output.

You could use a temporary file to store tr's output, and then mv it back, like this:

#!/usr/bin/env bash
for file in "/home/user/*"
do
    tr '[:lower:]' '[:upper:]' < "$file" > tmp_file
    mv tmp_file "$file"
done
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
-1

Here's how tr works:

[blah@exchange ~]# echo "SOMEthing" | tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
SOMETHING

So you can do:

cat input-file.txt | tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ > output-file.txt

or

cat $file | tr '[:lower:]' '[:upper:]' > tmp.txt && mv -f tmp.txt $file
Nick M
  • 2,424
  • 5
  • 34
  • 57