0

If I have a directory of files, where some files have an extension like .html and some files have no extension, how do I change them all to, e.g. .txt?

1

Believe this should work for you (probably more elegant ways to do this with sed).

for file in *; do
  base=`echo "${file%.*}"`
  mv -- "${file}" "${base}.txt"
done
  • 1
    @NoneHere I don't quite see why you need to echo and capture something in order to store it in a variable. Couldn't you just use ${file%.*} directly as the base? – John WH Smith Mar 4 '15 at 23:26
  • You are absolutely right John, the echo is unnecessary. Nice catch. – User52458 Mar 5 '15 at 14:35
  • One other thought for you AdamG - bear in mind that these solutions do not have any error control so conflict situations such as having files named "test" "test.html" and "test.csv" will have the above try to rename them all to test.txt... – User52458 Mar 5 '15 at 14:36
0

Not necessarily more elegant, but for completeness, here's a sed solution:

for file in *; do
  mv "$file" "$(echo "$file" | sed 's/^\(.*\)\.\?.*$/\1.txt/')"
done

The sed bit grabs everything before the last dot in the filename, and replaces the dot and whatever follows with '.txt'. If there is no dot in the filename, then '.txt' is just appended to the whole thing.

The quotes around the variables are important for handling filenames with spaces and such, regardless of which method you go with.

0

To rename all of them in the shell would be something like this:

for file in *; do
  mv -- "${file}" "`basename -- "${file}"`.txt"
done

You may want to test the type with file or other checks to determine the extensions.

  • This does not work. It only appends .txt to the file. I need to change some extensions, and add to others. – Adam_G Mar 4 '15 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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