linux重命名文件
We can use mv
command to change the file name. We can use it to change the file extension too. But, it works with a single file only and it doesn’t take wild characters.
我们可以使用mv
命令更改文件名。 我们也可以使用它来更改文件扩展名。 但是,它仅适用于单个文件,并且不带通配符。
We can create a shell script to change the extension of multiple files at once.
我们可以创建一个Shell脚本来一次更改多个文件的扩展名。
Linux Shell脚本更改多个文件的扩展名 (Linux Shell Script to Change Extension of Multiple Files)
Let’s look at the script code where we will use the mv command in a for loop to change the extension of all the files in the current directory.
让我们看一下脚本代码,我们将在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
Usage: multimove.sh doc txt
(to change all .doc to .txt)
用法 : multimove.sh doc txt
(将所有.doc更改为.txt)
测试重命名Shell脚本 (Testing the Rename Shell Script)
Below is the sample output from the above program execution.
下面是上述程序执行的示例输出。
$ 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
$
脚本假设和局限性 (Script Assumptions and Limitations)
- The files have only one period (.) 文件只有一个句点(。)
- It loops through all files in the current directory only. However, you can extend it to look for files in the child directories also. 它仅循环遍历当前目录中的所有文件。 但是,您可以扩展它以在子目录中查找文件。
- Whitespaces in the file name can cause a problem with the script. It has worked on my system with filenames having spaces but I can’t guarantee that it will work for you too. 文件名中的空格可能会导致脚本出现问题。 它已在我的系统上使用带有空格的文件名运行,但我不能保证它也会对您有用。
Further Readings: Linux mv command
深度阅读: Linux mv命令
翻译自: https://www.journaldev.com/118/linux-rename-multiple-files-extension
linux重命名文件