mv
を使用できます ファイル名を変更するコマンド。これを使用して、ファイル拡張子を変更することもできます。ただし、1つのファイルでのみ機能し、ワイルド文字は使用しません。
複数のファイルの拡張子を一度に変更するシェルスクリプトを作成できます。
複数のファイルの拡張子を変更するLinuxシェルスクリプト
forループでmvコマンドを使用して、現在のディレクトリ内のすべてのファイルの拡張子を変更するスクリプトコードを見てみましょう。
#!/bin/sh
#Save the file as multimove.sh
IFS=$'\n'
if [ -z "$1" ] || [ -z "$2" ]
then
echo "Usage: multimove oldExtension newExtension"
exit -1
fi
# Loop through all the files in the current directory
# having oldExtension and change it to newExtension
for oldFile in $(ls -1 *.${1})
do
# get the filename by stripping off the oldExtension
filename=`basename "${oldFile}" .${1}`
# determine the new filename by adding the newExtension
# to the filename
newFile="${filename}.${2}"
# tell the user what is happening
echo "Changing Extension \"$oldFile\" --> \"$newFile\" ."
mv "$oldFile" "$newFile"
done
使用法 :multimove.sh doc txt
(すべての.docを.txtに変更するため)
名前変更シェルスクリプトのテスト
以下は、上記のプログラム実行からの出力例です。
$ ls
abc.txt hi.doc journaldev.doc multimove.sh
$ ./multimove.sh doc txt
Changing Extension "hi.doc" --> "hi.txt" .
Changing Extension "journaldev.doc" --> "journaldev.txt" .
$ ls
abc.txt hi.txt journaldev.txt multimove.sh
$ ./multimove.sh txt doc
Changing Extension "abc.txt" --> "abc.doc" .
Changing Extension "hi.txt" --> "hi.doc" .
Changing Extension "journaldev.txt" --> "journaldev.doc" .
$ ls
abc.doc hi.doc journaldev.doc multimove.sh
$

スクリプトの前提と制限
- ファイルのピリオドは1つだけです(。)
- 現在のディレクトリ内のすべてのファイルのみをループします。ただし、これを拡張して、子ディレクトリ内のファイルを検索することもできます。
- ファイル名に空白があると、スクリプトで問題が発生する可能性があります。スペースを含むファイル名で私のシステムで機能しましたが、あなたにも機能することを保証することはできません。
参考資料: Linuxmvコマンド