9

Bash 脚本递归查询批量修改文件名

 3 years ago
source link: https://wsgzao.github.io/post/bash-recursive/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

需求是批量修改 .crt 和 .key 为 ssl.chain.crt 和 server.key,为什么会有这样的需求主要是踩了一个大坑 Sectigo AddTrust External CA Root Expiring May 30, 2020,说多了都是泪。

2020 年 05 月 31 日 - 初稿

阅读原文 - https://wsgzao.github.io/post/bash-recursive/


  1. 需要遍历目录
  2. 需要重命名 .key 和 .crt 结尾的文件为 server.key 和 ssl.chain.crt

linux 命令 递归修改文件名 (包括文件夹)

网上搜索了关键词,发现这个脚本写得比较清晰,但还是需要修改下

#!/bin/bash

function changeName(){
#new=`echo $1|sed 's/^/abc/g'`
new=`echo $1|sed -r 's/abc(.*$)/\1/g'`
echo changeName old: $1 new: $new
if [ $1 != $new ];then
mv $1 $new
fi
}

function travFolder(){
#echo "travFolder start"
flist=`ls $1`
cd $1
for f in $flist
do
#echo traverse do $f
local old=$f
if test -d $f
then
#echo "traverse dir:${f}"
travFolder $f
#echo "traverse rename dir:${f}"
changeName $old #rename folder
else
#echo "traverse file:$f"
changeName $f
fi
done
cd ../
}

param=$1
if [ -z "$1" ]
then
param="./"
echo "empty string: $param"
else
param=$1
fi
travFolder $param

修改后的代码

如果你考虑使用 rename 简化代码,可以参考 Stack Overflow 的一篇文章

How to Batch Rename Files in a macOS Terminal?

#!/bin/bash

function travFolder(){
#echo "travFolder start"
flist=`ls $1`
cd $1
for f in *.key; do mv "$f" "server.key"; done
for f in *.crt; do mv "$f" "ssl.chain.crt"; done
for f in $flist
do
#echo traverse do $f
if test -d $f
then
#echo "traverse dir:${f}"
travFolder $f
fi
done
cd ../
}

param=$1
if [ -z "$1" ]
then
param="./"
echo "empty string: $param"
else
param=$1
fi
travFolder $param

Bash 教程
linux 命令 递归修改文件名 (包括文件夹)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK