0

I have lots of files that need an extension appended to them but they are in a directory with lots of subdirectories. Currently the files have no extension at all. How would I rename just the files but not rename any of the directories or subdirectories?

Kevin
  • 3

1 Answers1

3

Iterate all and test whether it's a regular file or not.

#bash
for file in ./*; do
    [[ -f $file ]] && mv "$file" "$file.ext"
done

In case you need to avoid adding extension on files that already have it:

for file in ./*; do
    if [[ -f $file && $file != *.ext ]]; then
        mv "$file" "$file.ext"
    fi
done
geirha
  • 46,101
  • 1
    For some reason this script ignores file names that include spaces in them, is there anyway to include them as well? – Kevin Jun 20 '12 at 19:00
  • @Kevin, it should handle them just fine. Did you modify anything? If you remove any of the "-quotes, it will fail on filenames containing whitespace or other syntactical characters. – geirha Jun 21 '12 at 00:02
  • @geirha shouldn't -f $file have quotes as well ? – Sergiy Kolodyazhnyy Jun 01 '15 at 10:31
  • @Serg With [ ... ] instead, then quotes would be necessary, but [[ ... ]] is a shell keyword and is parsed differently, so quotes there are optional. See BashFAQ 31 for more on the differences. – geirha Jun 01 '15 at 12:33