Trimming a part of file extension for all the files in directory - Linux

巧了我就是萌 提交于 2021-02-05 08:45:15

问题


I have a requirement in which I want to trim the file extension for all the files contained in a directory: -

The file will be like;

America.gz:2170
Europe.gz:2172
Africa.gz:2170
Asia.gz:2172

what I need is to trim the :2170 and :2172 from all the files, so that only the .gz extension remains.

I know that with the help of below SED code, it is possible for all the entries in a file, however I need for all the files in a directory: -

**sed 's/:.*//' file**

Any bash or awk code to fix this will be highly appreciated.

Thanks in advance.


回答1:


You can do this in bash:

shopt -s nullglob
for f in *.gz:*; do
    mv -- "$f" "${f%:*}"
done

"${f%:*}" will remove everything after : on RHS of variable $f




回答2:


You may use rename command.

rename 's/:.*//' *.gz:*

or

rename 's/:[^:]*$//' *.gz:*



回答3:


This entire job can be done with a for loop and the substring processing operator '%':

"${parameter%word} Remove Smallest Suffix Pattern."

#!/bin/sh

for i in *
do #mv "$i" "${i%:}"
   echo " mv $i ${i%:*}"
done


来源:https://stackoverflow.com/questions/32997749/trimming-a-part-of-file-extension-for-all-the-files-in-directory-linux

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