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

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


当前回答

我用。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
~$

其他回答

类似于之前的建议,我是这样做的:

find . -name '*OldText*' -exec sh -c 'mv "$0" "${0/OldText/NewText}"' {} \;

我首先用

find . -name '*OldText*' -exec sh -c 'echo mv "$0" "${0/OldText/NewText}"' {} \;

如果你更喜欢PERL,这里有一个简短的PERL脚本(最初由PERL的创造者Larry Wall编写),它将完全满足你的需求: tips.webdesign10.com/files/rename.pl.txt。

对于你的例子,下面的方法应该可以奏效:

rename.pl 's/html/txt/' *.html

这里有一个解决方案,使用AWK。确保文件存在于工作目录中。否则,cd到html文件所在的目录,然后执行以下命令:

for i in $(ls | grep .html); do j=$(echo $i | grep -oh "^\w*." | awk '{print $1"txt"}'); mv $i $j; done

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

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

试试这个

rename .html .txt *.html 

用法:

rename [find] [replace_with] [criteria]