在一个目录中,我有一些*.html文件。我想把它们都重命名为*.txt

我该怎么做呢?我使用bash shell。


当前回答

你也可以在Bash中创建一个函数,将它添加到。bashrc或其他文件中,然后在任何你想使用的地方使用它。

change-ext() {
    for file in *.$1; do mv "$file" "$(basename "$file" .$1).$2"; done
}

用法:

change-ext css scss

源代码的功能:https://stackoverflow.com/a/1224786/6732111

其他回答

有点晚了。你可以用xargs:

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

或者你所有的文件都在某个文件夹里

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

这个问题明确提到了Bash,但如果你恰好有可用的ZSH,它是相当简单的:

zmv '(*).*' '$1.txt'

如果你得到zsh:命令没有找到:zmv,然后简单地运行:

autoload -U zmv

然后再试一次。

感谢这篇关于zmv的原创文章。

如果使用bash,则不需要使用sed、basename、rename、expr等外部命令。

for file in *.html
do
  mv "$file" "${file%.html}.txt"
done

我用。bashrc写了这段代码

alias find-ext='read -p "Path (dot for current): " p_path; read -p "Ext (unpunctured): " p_ext1; find $p_path -type f -name "*."$p_ext1'
alias rename-ext='read -p "Path (dot for current): " p_path; read -p "Ext (unpunctured): " p_ext1; read -p "Change by ext. (unpunctured): " p_ext2; echo -en "\nFound files:\n"; find $p_path -type f -name "*.$p_ext1"; find $p_path -type f -name "*.$p_ext1" -exec sh -c '\''mv "$1" "${1%.'\''$p_ext1'\''}.'\''$p_ext2'\''" '\'' _ {} \;; echo -en "\nChanged Files:\n"; find $p_path -type f -name "*.$p_ext2";'

在"/home/<user>/example-files"这样的文件夹中:

/home/<用户> /示例文件: 中 file2.txt file3.pdf file4.csv

命令的行为是这样的:

~$ find-text
Path (dot for current): example-files/
Ext (unpunctured): txt

example-files/file1.txt
example-files/file2.txt


~$ rename-text
Path (dot for current): ./example-files
Ext (unpunctured): txt
Change by ext. (unpunctured): mp3

Found files:
./example-files/file1.txt
./example-files/file1.txt

Changed Files:
./example-files/file1.mp3
./example-files/file1.mp3
~$

使用rename命令的示例如下:

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

-n表示它是测试运行,不会实际更改任何文件。它将向您显示删除-n后将重命名的文件列表。在上面的例子中,它将当前目录中的所有文件从扩展名为.htm的文件转换为.html。

如果上面测试运行的输出看起来没问题,那么你可以运行最终版本:

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

-v是可选的,但是包含它是个好主意,因为它是你通过rename命令所做的更改的唯一记录,如下面的示例输出所示:

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

中间的棘手部分是使用正则表达式的Perl替换,如下所示:

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