在 Linux 中保留扩展名的同时重命名文件? [英] Rename file while keeping the extension in Linux?

查看:42
本文介绍了在 Linux 中保留扩展名的同时重命名文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目录,其中包含具有不同扩展名(pdf、doc、txt...等)的多个文件.

I have a directory that contains multiple files with different extensions (pdf, doc, txt...etc).

我正在尝试根据目录名称重命名所有文件,同时保持文件扩展名相同.如果所有文件都是 PDF,则下面的代码工作正常,否则它也会将 txt 文件扩展名更改为 pdf.

I'm trying to rename all files according to the directory name while keeping the file extension the same. The code below works fine if all files are PDF otherwise it will change txt file extension to pdf too.

如何在保留文件扩展名的同时重命名文件

How can I rename files while preserving the file extension

mv "$file" "${dir}/${dir}-${count}.pdf"

推荐答案

你可以通过 bash 做到这一点.

you can do this through bash.

能否请您提供更多详细信息.你如何决定这个 $dir 和 $count 变量值.

can you please provide more details. how your deciding this $dir and $count variable value.

如果您已经知道要更改文件名,如下所示

if you already know by what you want to change the file name like below

旧名称|新名称|路径

test.1|newtest.1|路径

test.1|newtest.1|Path

arty.2|xyz.2|路径

arty.2|xyz.2|Path

如果你想用特定的名字替换它,那么你可以准备一个像上面那样的列表,然后通过 while 或 for 循环遍历文件.下面是简单的 bash 片段,用于在多个目录下有文件的情况

if you want to replace it by specific names then you can prepare a list like above and then traverse through the file by while or for loop. below is simple bash snippet for case where you have files under multiple directory

while IFS="|" read OLD NEW PATH
do
    cd $Path

    filename=`echo $NEW|awk -F '.' '{print $1}'`

    filetype=`echo $NEW|awk -F '.' '{print $2}'`

    mv $OLD $filename.$filetype

done<FILE_PATH

如果想在单个目录下执行操作,那么下面的代码片段将起作用.

if want to perform operation under single directory then below snippet will work.

for i in $(ls /tmp/temp)
do 
    filename=`echo $i|awk -F "." '{print $1}'`
    fileType=`echo $i|awk -F "." '{print $2}'`
    mv $i $filename.$fileType
done

这篇关于在 Linux 中保留扩展名的同时重命名文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆