如何删除某个目录中文件名的最后n个字符(在Mac终端中)-UNIX? [英] How can I remove the last n characters of filenames in a certain directory (in Mac terminal)- unix?

查看:43
本文介绍了如何删除某个目录中文件名的最后n个字符(在Mac终端中)-UNIX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用"mv"进行重命名,因为重命名"命令在我的Mac终端中不起作用.

I am trying to rename using "mv", because "rename" command doesn't work in my Mac terminal.

我有一堆名为

DTM001_ACGGT-TTAGGC.fq
DTM156_GGTTG-ACAGTG.fq

...等

我希望将其重命名为

DTM001.fq
DTM156.fq

我想更简单的方法是删除文件扩展名前的最后13个字符?

I suppose the easier way is to remove the last 13 characters before the file extension?

我尝试了以下链接:

但没有一个对我有用,可能是因为我不完全了解如何为我的特定情况处理答案,或者某些答案使用了我无法访问的重命名"命令.

but none have worked for me, perhaps because I do not fully understand how to manipulate the answers for my specific case or some answers use "rename" command which I cannot access.

推荐答案

macOS Terminal只是与称为shell的交互式程序的接口.默认外壳程序名称为 bash .

The macOS Terminal is simply an interface to an interactive program called a shell. The default shell's name is bash.

您要查找的东西称为shell脚本或bash脚本,用于重命名文件.

What you are looking for is known as a shell script, or a bash script, to rename files.

您引用的问题有答案.重申:

The questions you referenced have the answer. To reiterate:

cd directory_with_the_files
for file in *.fq; do
    mv -vn "${file}" "${file%_*}.fq"
done

您可以在命令行中全部输入,或将其放入文件中并执行以下操作:

You can type this all in at the command line, or place it into a file and execute it with:

bash file_containing_the_commands

这将遍历当前目录中的所有 .fq 文件,并将它们重命名为您想要的文件. mv -v 选项只是意味着在重命名发生时打印重命名(知道它正在做某事很有用),以及 -n 标志意味着不要意外覆盖任何文件(以防您输入错误或遇到重复的数字).

This will go through all .fq files in the current directory, renaming them to what you want. The -v option to mv simply means to print the rename as it happens (useful to know that it's doing something), and the -n flag means don't accidentally overwrite any files (in case you type something in wrong or come across duplicate numbers).

所有的魔术都在 $ {file%_ *}.fq 中发生,其中显示删除第一个 _ 之后的所有内容,然后再添加 .fq ."这称为外壳参数扩展",您可以在 Bash参考手册.它的措辞有些令人费解,但这是此特定用例的相关内容:

All the magic is happening in the ${file%_*}.fq, which says "remove everything after the first _ and add the .fq back". This is known as a "shell parameter expansion," which you can read more about in the Bash Reference Manual. It's somewhat obtusely worded, but here is the relevant bit to this particular use case:

$ {参数单词}

单词被扩展以产生一个模式与文件名扩展一样.如果模式匹配 parameter 的扩展值的尾部,然后是结果扩展的是匹配最短的 parameter 的值模式(以%"为例)已删除.

The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the '%' case) deleted.

这篇关于如何删除某个目录中文件名的最后n个字符(在Mac终端中)-UNIX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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