How do I rename the extension for a batch of files

2019-01-04 15:29发布

In a directory, I have a bunch of *.html files.

I'd like to rename them all to *.txt

I use the bash shell.

18条回答
太酷不给撩
2楼-- · 2019-01-04 16:00

For an better solution (with only bash functionality, as opposed to external calls), see one of the other answers.


The following would do and does not require the system to have the rename program (although you would most often have this on a system):

for file in *.html; do
    mv "$file" "$(basename "$file" .html).txt"
done

EDIT: As pointed out in the comments, this does not work for filenames with spaces in them without proper quoting (now added above). When working purely on your own files that you know do not have spaces in the filenames this will work but whenever you write something that may be reused at a later time, do not skip proper quoting.

查看更多
Lonely孤独者°
3楼-- · 2019-01-04 16:00

This worked for me on OSX from .txt to .txt_bak

find . -name '*.txt' -exec sh -c 'mv "$0" "${0%.txt}.txt_bak"' {} \;
查看更多
看我几分像从前
4楼-- · 2019-01-04 16:01

On a Mac...

  1. Install rename if you haven't: brew install rename
  2. rename -S .html .txt *.html
查看更多
【Aperson】
5楼-- · 2019-01-04 16:04

After someone else's website crawl, I ended up with thousands of files missing the .html extension, across a wide tree of subdirectories.

To rename them all in one shot, except the files already having a .html extension (most of them had none at all), this worked for me:

cd wwwroot
find . -xtype f \! -iname *.html   -exec mv -iv "{}"  "{}.html"  \;  # batch rename files to append .html suffix IF MISSING

In the OP's case I might modify that slightly, to only rename *.txt files, like so:

find . -xtype f  -iname *.txt   -exec filename="{}"  mv -iv ${filename%.*}.{txt,html}  \; 

Broken down (hammertime!):

-iname *.txt
- Means consider ONLY files already ending in .txt

mv -iv "{}.{txt,html}" - When find passes a {} as the filename, ${filename%.*} extracts its basename without any extension to form the parameters to mv. bash takes the {txt,html} to rewrite it as two parameters so the final command runs as: mv -iv "filename.txt" "filename.html"

Fix needed though: dealing with spaces in filenames

查看更多
Summer. ? 凉城
6楼-- · 2019-01-04 16:04

This is a good way to modify multiple extensions at once:

for fname in *.{mp4,avi}
do
   mv -v "$fname" "${fname%.???}.mkv"
done

Note: be careful at the extension size to be the same (the ???)

查看更多
劳资没心,怎么记你
7楼-- · 2019-01-04 16:06

The command mmv seems to do this task very efficiently on a huge number of files (tens of thousands in a second). For example, to rename all .xml files to .html files, use this:

mmv ";*.xml" "#1#2.html"

the ; will match the path, the * will match the filename, and these are referred to as #1 and #2 in the replacement name.

Answers based on exec or pipes were either too slow or failed on a very large number of files.

查看更多
登录 后发表回答