shell 实现批量重命名
1. 方案一
rename 's/.x$//' *.x # 暂未测试通过
2. 方案二
for f in `ls`;do mv -f $f `echo $f|sed 's/.x//'`; done
3. 方案三
sudo cat <<-'EOF'>/bin/batchrename
#!/bin/bash
# Copyright (c) 2017 ~ 2025, the original author wangl.sir individual Inc,
# All rights reserved. Contact us <wanglsir@gmail.com, 983708408@qq.com>
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
set -e
function moveName() {
local oldFname=$1
local srcStr=$2
local dstStr=$3
local newFname=$(echo $oldFname|sed "s/$srcStr/$dstStr/g")
if [ $oldFname != $newFname ];then
echo "moving: $PWD {$oldFname => $newFname}"
mv $oldFname $newFname
fi
}
function walkFolder() {
local currDir=$1
local srcStr=$2
local dstStr=$3
local fnames=$(ls $currDir)
cd $currDir
for fname in $fnames
do
local oldFname=$fname # Notes!
if test -d $fname; then
walkFolder $fname $srcStr $dstStr # First move childrens
moveName $oldFname $srcStr $dstStr
else
moveName $fname $srcStr $dstStr
fi
done
cd ../
}
# --- Main. ---
usage="Usage: $(echo `basename $0`) [rootDir] <srcStr> <dstStr>"
if [ $# -ge 3 ]; then
rootDir=$1
srcStr=$2
dstStr=$3
elif [ $# -ge 2 ]; then
echo "Tips: Use the current '$PWD' to renames the start root directory."
rootDir="$PWD"
srcStr=$1
dstStr=$2
else
echo "$usage"; exit -1
fi
[ -z "$srcStr" ] && echo "srcStr is required! $usage" && exit -1
[ -z "$dstStr" ] && echo "dstStr is required! $usage" && exit -1
walkFolder $rootDir $srcStr $dstStr
EOF
sudo chmod +x /bin/batchrename
batchrename