使用shell脚本更改文件扩展名

Mai*_*nak 6 unix linux shell

如何将目录中所有*.dat文件的扩展名更改为*.txt.Shell脚本应将目录名称作为参数.可以将多个目录作为参数.在具有日期和时间戳的附加模式下打印命令结果的日志.

Pbe*_*ben 19

批处理文件在Unix中通过文件扩展名重命名

# change .htm files to .html
for file in *.htm ; do mv $file `echo $file | sed 's/\(.*\.\)htm/\1html/'` ; done

# change .html files to .htm
for file in *.html ; do mv $file `echo $file | sed 's/\(.*\.\)html/\1htm/'` ; done

#change .html files to .shtml
for file in *.html ; do mv $file `echo $file | sed 's/\(.*\.\)html/\1shtml/'` ; done

#change .html files to php
for file in *.html ; do mv $file `echo $file | sed 's/\(.*\.\)html/\1php/'` ; done
Run Code Online (Sandbox Code Playgroud)

所以==>

# change .dat files to .txt
for file in *.dat ; do mv $file `echo $file | sed 's/\(.*\.\)dat /\1txt/'` ; done
Run Code Online (Sandbox Code Playgroud)

  • mv $ file $ {file%.dat} .txt#know your shell builtin cruft (15认同)
  • @Kaz,最好使用`$ {file %% <EXT>}`,因为有人可能会有类似`all.html.files.tar.gz'的内容. (2认同)

Aki*_*nen 11

Bash可以完成所有繁重的工作,例如提取扩展和标记新的扩展.例如:

for file in $1/*.dat ; do mv "$file" "${file%.*}.txt" ; done
Run Code Online (Sandbox Code Playgroud)

  • 欢迎来到堆栈溢出!虽然此代码片段可以解决问题,但[包括解释](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而那些人可能不知道您建议代码的原因。 (2认同)

Ale*_*lex 8

#!/bin/bash
for d in $*; do
    for f in $(ls $d/*.dat); do
        echo $(date) $(mv -v $f ${f%.dat}.txt)
    done
done
Run Code Online (Sandbox Code Playgroud)

运行脚本时,shell应该完成输出重定向

退出参数有效性检查