Rename multiple files while keeping the same extension on Linux

廉价感情. 提交于 2021-02-13 16:37:09

问题


I have 100s of files in a directory with the following naming convention.

00XYZCD042ABCDE20141002ABCDE.XML
00XYZCC011ABCDE20141002.TXT
00XYZCB165ABCDE20141002ABCDE.TXT
00XYZCB165ABCDE20141002ABCDE.CSV

I want to rename these files using bash, awk, cut, sed, so that I get the output:

XYZCD042.XML
XYZCC011.TXT
XYZCB165.TXT
XYZCB165.CSV

So basically, remove the first two 0s always, and then keep everything until ABCDE starts and then remove everything including ABCDE and keep the file extension.


回答1:


You could try the below rename command,

rename 's/ABCDE.*(\..*)/$1/;s/^00//' *

Explanation:

  • s/ABCDE.*(\..*)/$1/ Matches all the characters from the first ABCDE upto the last and captures only the extension part. Then all the matched chars are replaced with that captured extension.
  • s/^00// Then this would remove the leading two zeros.



回答2:


Bash only:

for fn in *; do
    A=${fn#00}
    mv $fn ${A/ABCDE*./.}
done

The first line in the for loop strips the 00 prefix, and the second line strips the ABCDE suffix (up to a dot), then performs the rename.




回答3:


for file in *
do
    mv -- "$file" "${file:2:8}.${file#*.}"
done

It's important to always quote your variables unless you have a specific purpose in mind and understand all of the effects.




回答4:


for i in *; do
    mv $i $(echo $i | sed -e 's/^00//' -e 's/ABCDE2014[^.]*//');
done


来源:https://stackoverflow.com/questions/26178469/rename-multiple-files-while-keeping-the-same-extension-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!