In the morning I wanted to upload some photos to the album, but because all the photos have the extension is jpg rather than lowercase jpg, resulting in "malformed" and can not upload photos. The question now arises: how do you use a shell script to bulk change all file extension jpg to lowercase jpg?
Now that you want to replace the file name in batches, you must iterate through each file in the specified directory with a for loop. For each file, if the name of the file is Name.oldext, then we have to dig out the name in the original file name and then splice it with the new file extension newext to form a new filename name.newext. In this way, the following script was born:
Copy Code code as follows:
#!/bin/bash
oldext= "JPG"
newext= "JPG"
dir=$ (eval pwd)
For file in $ (ls $dir | grep. $oldext)
Todo
name=$ (ls $file | cut-d.-f1)
MV $file ${name}. $newext
Done
echo "Change Jpg=====>jpg done!"
Here's a brief description of the program:
1. Variable oldext and Newext specify the old extension and the new extension respectively. DIR Specifies the directory where the file resides;
2. "LS $dir | grep. $oldext is used to get all files with the old extension in the specified directory dir;
3. Use the Cut command to place the file name "." In the recycle body first. The previous string is clipped and assigned to the name variable, and the current file name is renamed to the new file name.
With this script, the extensions for all photos were successfully modified. To make this script more generic, we can add a few read commands to implement the interaction between the script and the user. The improved version of the script is as follows:
Copy Code code as follows:
#!/bin/bash
Read-p "old extension:" Oldext
Read-p "New extension:" Newext
Read-p "The Directory:" dir
CD $dir
For file in $ (ls $dir | grep. $oldext)
Todo
name=$ (ls $file | cut-d.-f1)
MV $file ${name}. $newext
echo "$name. $oldext ====> $name. $newext"
Done
echo "All files has been modified."
Attached: Another version
Copy Code code as follows:
#!/bin/sh
# file Name:rename_suffix.sh
# Author:zhouhh
# email:ablozhou@gmail.com
# date:2008.4.1
echo "Input what suffix'll be replaced:"
Read Suffix_src
echo "Input what suffix of file to rename to:"
Read SUFFIX_DST
For i in *. $SUFFIX _src
Todo
If [-e $i]; Then
echo "MV $i to ' basename $i $SUFFIX _src '. $SUFFIX _dst"
MV $i ' basename $i $SUFFIX _src '. $SUFFIX _dst
Else
echo "file does not exist."
Exit-1
Fi
Done