Bash script recursive query batch modify file name

Time:2020-8-1

preface

Requirement is batch modification. CRT and. key is ssl.chain.crt and server.key The main reason why there is such a demand is that sectigo addtrust external CA root expiring May 30, 2020 is full of tears.

Update history

May 31, 2020 – first draft

Read the original- https://wsgzao.github.io/post…


Thinking of problem solving

  1. You need to traverse the directory
  2. Need to rename. key andThe file at the end of. CRT is server.key and ssl.chain.crt

Linux commands recursively modify file names (including folders)

Search for keywords online, found that the script is clear, but still need to be modified

#!/bin/bash

function changeName(){
    #new=`echo $1|sed 's/^/abc/g'`
    new=`echo $1|sed -r 's/abc(.*$)//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

Modified code

If you consider using rename to simplify your code, you can refer to an article in 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

Reference articles

Bash tutorial
Linux commands recursively modify file names (including folders)