遍历目录修改文件名

环境

Debian10

要求

指定目录下所有文件名中的 . 改为 _。

比如某个目录保存都是 pdf 文件,pdf 命名的例子为 a.b.c.d.pdf,现在要修改为 a_b_c_d.pdf。

实现

利用shell脚本实现。

#!/bin/bash
function changeName(){
  new=`echo $1|sed 's/\./_/g'`
  mv $1 $new
  new1=`echo $new|sed 's/_pdf/\.pdf/g'`
  echo "change file name from $1 to $new1"
  mv $new $new1
}

function changeBack() {
  new=`echo $1|sed 's/_/\./g'`
  mv $1 $new
  echo "change file name from $1 to $new" 
}

function travFolder(){ 
  #echo "travFolder"
  flist=`ls $1`
  cd $1
  #echo $flist
  for f in $flist
  do
    if test -d $f
    then
      #echo "dir:$f"
      echo "enter direction name: $f"
      travFolder $f
    else
      if [ "${f##*.}"x = "pdf"x ]; then
        #echo "$file:$f" 
        changeName $f
	#changeBack $f
      fi
    fi
  done
  cd ../ 
}

if [ $# -ge 1 ]; then
  echo "enter direction name: $1"
  travFolder $1
else
  echo "=================================================="
  echo "usage: cname abc"
  echo "abc means which direction you want to change"
  echo "=================================================="
fi

知识点

sed命令

sed 's/source/destination/g

注意:

source为需要替换的字符。

destination为替换后的目标字符。

进一步 sed 命令教程,请参考https://www.runoob.com/linux/linux-comm-sed.html

if命令

进一步 if 命令教程,请参考https://www.runoob.com/linux/linux-shell-process-control.html

Shell参数

进一步 Shell 参数教程,请参考https://www.runoob.com/linux/linux-shell-passing-arguments.html

扫描二维码关注公众号,回复: 9058972 查看本文章
发布了138 篇原创文章 · 获赞 7 · 访问量 41万+

猜你喜欢

转载自blog.csdn.net/justidle/article/details/103737849