Linux 下批量修改刪除文件名中不想要的字段


Linux 下批量修改刪除文件名中不想要的字段

本文重點

${var%ABC} ${var#ABC}  % 表示從變量值尾部刪除至ABC
# 表示從變量值頭部刪除至ABC
 
        

案例1:

有如下文件想要刪除_bak

[root@hsun hook]# ls
postCreateUser.sh               preCreateUser.sh
postDeleteUser_bak.sh           preDeleteUser_bak.sh
postDisableUser_bak.sh          preDisableUser_bak.sh
postEnableUser_bak.sh           preEnableUser_bak.sh
postUpdateUserAttribute_bak.sh  preUpdateUserAttribute_bak.sh

 

然后使用shell

for var in *_bak.sh; do mv "$var" "${var%_bak.sh}.sh"; done

[root@hsun hook]# ls
postCreateUser.sh           preCreateUser.sh
postDeleteUser.sh           preDeleteUser.sh
postDisableUser.sh          preDisableUser.sh
postEnableUser.sh           preEnableUser.sh
postUpdateUserAttribute.sh  preUpdateUserAttribute.sh

 

個人理解:
1、首先將文件夾內的文件提取到變量var中,然后使用mv命令將$var重命名為${var%_bak.sh}.sh

2、"${var%_bak.sh}.sh"首先從變量的尾部刪除到_bak.sh,此時所有文件都會刪除_bak.sh然后在${var%_bak.sh}最后加上.sh就重命名完成。

分步解讀:

  單拿一個文件postEnableUser_bak.sh舉例子

  第一步,首先拿到文件名為postEnableUser_bak.sh的文件

  第二步,刪除文件后邊的_bak.sh。此時文件名已變成了postEnableUser

  第三步,在修改好的文件名后邊加.sh。最后文件名就成為了postEnableUser.sh

所以它的文件名變化順序為:

    postEnableUser_bak.sh  -->  postEnableUser  --> postEnableUser.sh

 

實際案例2

想要刪除下列文件中的source-wuxi 並且替換成source-xibei.

[root@hsun sss]# ls
sink-xibei-auth.properties        source-wuxi-online.properties
source-beijing-auth.properties    source-wuxi-project.properties
source-wuxi-applyinfo.properties  source-wuxi-projectusers.properties
source-wuxi-lshosts.properties    source-xibei-applaunch.properties
source-wuxi-metrics.properties

[root@hsun sss]# for var in source-wuxi*;do mv "${var}" "source-xibei${var#source-wuxi}";done
[root@hsun sss]# ls
sink-xibei-auth.properties         source-xibei-metrics.properties
source-beijing-auth.properties     source-xibei-online.properties
source-xibei-applaunch.properties  source-xibei-project.properties
source-xibei-applyinfo.properties  source-xibei-projectusers.properties
source-xibei-lshosts.properties

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM