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条回答
Evening l夕情丶
2楼-- · 2019-01-04 15:39

A bit late to the party. You could do it with xargs:

ls *.html | xargs -I {} sh -c 'mv $1 `basename $1 .html`.txt' - {}

Or if all your files are in some folder

ls folder/*.html | xargs -I {} sh -c 'mv $1 folder/`basename $1 .html`.txt' - {}
查看更多
虎瘦雄心在
3楼-- · 2019-01-04 15:40
rename 's/\.html$/\.txt/' *.html

does exactly what you want.

查看更多
你好瞎i
4楼-- · 2019-01-04 15:40

You want to use rename :

rename -S .html .txt *.html

This does exactly what you want - it will change the extension from .html to .txt for all files matching *.html.

Note: Greg Hewgill correctly points out this is not a bash builtin; and is a seperate Linux command. If you just need something on Linux this should work fine; if you need something more cross-platform then take a look at one of the other answers.

查看更多
Fickle 薄情
5楼-- · 2019-01-04 15:40

Unfortunately it's not trivial to do portably. You probably need a bit of expr magic.

for file in *.html; do echo mv -- "$file" "$(expr "$file" : '\(.*\)\.html').txt"; done

Remove the echo once you're happy it does what you want.

Edit: basename is probably a little more readable for this particular case, although expr is more flexible in general.

查看更多
贼婆χ
6楼-- · 2019-01-04 15:44

This is the slickest solution I've found that works on OSX and Linux, and it works nicely with git too!

find . -name "*.js" -exec bash -c 'mv "$1" "${1%.js}".tsx' - '{}' \;

and with git:

find . -name "*.js" -exec bash -c 'git mv "$1" "${1%.js}".tsx' - '{}' \;

查看更多
▲ chillily
7楼-- · 2019-01-04 15:45

Here is an example of the rename command:

rename -n ’s/\.htm$/\.html/’ *.htm

The -n means that it's a test run and will not actually change any files. It will show you a list of files that would be renamed if you removed the -n. In the case above, it will convert all files in the current directory from a file extension of .htm to .html.

If the output of the above test run looked ok then you could run the final version:

rename -v ’s/\.htm$/\.html/’ *.htm

The -v is optional, but it's a good idea to include it because it is the only record you will have of changes that were made by the rename command as shown in the sample output below:

$ rename -v 's/\.htm$/\.html/' *.htm
3.htm renamed as 3.html
4.htm renamed as 4.html
5.htm renamed as 5.html

The tricky part in the middle is a Perl substitution with regular expressions, highlighted below:

rename -v ’s/\.htm$/\.html/’ *.htm
查看更多
登录 后发表回答