1

I have a directory containing lot of files - txt and others. I want to change extension those others file to txt

For now - i use this:

find . ! -name '*.txt' -type f -exec ls -f {} + > to_txt.txt
for i in ``cat to_txt.txt``; do 
    mv $i $i.txt && echo $i "File extension have been changed" || echo "Something went wrong"
done;
rm to_txt.txt

Script works fine, but i think it is clumsy Is there any smarter and elegant way to do this?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Fangir
  • 131
  • 6
  • 16

1 Answers1

2

Just use the -exec to perform the mv command:

find . ! -name '*.txt' -type f -exec mv {} {}.txt \;
#                                    ^^^^^^^^^^^^
#                                    here the magic

How does this work?

find . ! -name '*.txt' -type f is what you already had: it looks for those files whose name does not end with .txt.

Then, the key is the usage of -exec: there, we make use of {} that carries the value of every file that has been found. Since it acts as a variable, you can use it as so and perform commands. In this case, you want to do mv $file $file.txt, so this is what we do: mv {} {}.txt. To have it work, we finally have to add the \; part.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Works great ;) aint wont to abuse your kindness, but could you give me a little explanation, what did you do here? Try to understand by `man find`, but with little result – Fangir May 23 '16 at 18:49
  • thak you very much ;) do i understand it correctly - until add `\:` on the end of the line, i can use `{}` to store the file name as variables, and perform another operation? – Fangir May 23 '16 at 19:10
  • @Fangir well not really. You can use it once. If you want to do more things, you need to use `-exec sh -c ' ... '`. See for example http://stackoverflow.com/a/17789183/ – fedorqui May 23 '16 at 19:16