【问题标题】:How do I use perl-rename to replace . with _ on linux recursively, except for extensions如何使用 perl-rename 替换 .在 linux 上递归使用 _,扩展除外
【发布时间】:2021-05-31 00:36:37
【问题描述】:

我正在尝试以递归方式重命名一些文件和文件夹以格式化名称,并认为findperl-rename 可能是它的工具。我已经找到了大部分我想运行的命令,但最后两个:

  • 我希望将目录名称中的每个 . 替换为 _
  • 对于每个.,但文件名中的最后一个要替换为_

这样./my.directory/my.file.extension 就变成了./my_directory/my_file.extension

对于第二个任务,我什至没有命令。

对于第一个任务,我有以下命令: find . -type d -depth -exec perl-rename -n "s/([^^])\./_/g" {} + 其中重命名./the_expanse/Season 1/The.Expanse.S01E01.1080p.WEB-DL.DD5.1.H264-RARBG./the_expanse/Season 1/Th_Expans_S01E0_1080_WEB-D_DD__H264-RARBG,所以它不起作用,因为.之前的每个单词字符都被吃掉了。

如果改为输入: find . -type d -depth -exec perl-rename -n "s/\./_/g" {} +,我将./the_expanse/Season 1/The.Expanse.S01E01.1080p.WEB-DL.DD5.1.H264-RARBG 重命名为_/the_expanse/Season 1/The_Expanse_S01E01_1080p_WEB-DL_DD5_1_H264-RARBG,这也不起作用,因为当前目录被_ 替换。

如果有人能给我一个解决方案:

  • 将目录名称中的每个. 替换为_
  • _替换文件名中的每个.,但最后一个 我将不胜感激。

【问题讨论】:

  • 我认为,如果您阅读有关 find 工作原理的详细信息,您将能够调整您的第二个命令以执行您想要的操作。类似于将一些值传递给 -name 标志以仅查找不是“。”的目录。目录应该可以工作。

标签: linux command rename


【解决方案1】:

首先使用.处理目录

# find all directories and remove the './' part of each and save to a file
$ find -type d  | perl -lpe  's@^(\./|\.)@@g' > list-all-dir
# 
# dry run
# just print the result without actual renaming 
$ perl -lne '($old=$_) && s/\./_/g && print' list-all-dir
#
# if it looked fine, rename them
$ perl -lne '($old=$_) && s/\./_/g && rename($old,$_)' list-all-dir
 

这部分s/\./_/g 用于匹配每个. 并将其替换为_


第二处理文件扩展名,重命名. 除了. 为文件扩展名

# find all *.txt file and save or your match
$ find -type f -name \*.txt  | perl -lpe  's@^(\./|\.)@@g' > list-all-file
#
# dry run
$ perl -lne '($old=$_) && s/(?:(?!\.txt$)\.)+/_/g && print ' list-all-file
#
# if it looked fine, rename them
$ perl -lne '($old=$_) && s/(?:(?!\.txt$)\.)+/_/g && rename($old,$_) ' list-all-file

这部分(?:(?!\.txt$)\.)+用于匹配每个.,除了文件扩展名前的最后一个.


注意

这里我使用了.txt,你应该用你的匹配替换它。 Second 代码将像这样重命名输入:

/one.one/one.one/one.file.txt
/two.two/two.two/one.file.txt
/three.three/three.three/one.file.txt

到这样的输出:

/one_one/one_one/one_file.txt
/two_two/two_two/one_file.txt
/three_three/three_three/one_file.txt

您可以通过在线正则表达式匹配来测试here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-09
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 2015-07-24
    • 2020-08-13
    相关资源
    最近更新 更多