使用Bash重命名文件,删除前缀和后缀

编程入门 行业动态 更新时间:2024-10-23 20:20:00
本文介绍了使用Bash重命名文件,删除前缀和后缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用bash重命名一堆文件,以转换此文件模式:

I want to rename a bunch of files using bash, transforming this file pattern:

prefix - name - suffix.txt

进入这一个:

name.txt

为此,我编写了以下脚本:

For that I wrote the following script:

find . -name "*.txt" | while read f do mv "${f}" "${f/prefix - /}" done find . -name "*.txt" | while read f do mv "${f}" "${f/ - suffix/}" done

它可以工作,但是我想使用一个循环来执行重命名.有可能吗?

It works, but I'd like to perform the renaming using a single loop. Is it possible?

推荐答案

另一种使用正则表达式的方法很有趣:

Another approach, for fun, using regular expressions:

regex='prefix - (.*) - suffix.txt' for f in *.txt; do [[ $f =~ $regex ]] && mv "$f" "${BASH_REMATCH[1]}.txt" done

实际上,在这里使用简单模式'* .txt'存在两个问题:

Actually, using the simple pattern '*.txt' here has two problems:

  • 范围太广;您可能需要将正则表达式应用于许多不匹配的文件.
  • 如果当前目录中有很多个文件,则命令行可能会溢出.
  • It's too broad; you may need to apply the regex to a lot of non-matching files.
  • If there are a lot of files in the current directory, the command line could overflow.
  • 使用find使过程复杂,但更正确:

    Using find complicates the procedure, but is more correct:

    find . -maxdepth 1 -regex 'prefix - .* - suffix.txt' -print0 | \ while read -d '' -r; do [[ $REPLY =~ $regex ]] && mv "$REPLY" "${BASH_REMATCH[1]}.txt" done

    更多推荐

    使用Bash重命名文件,删除前缀和后缀

    本文发布于:2023-11-04 05:27:37,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1557071.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:前缀   后缀   重命名   文件   Bash

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!