bash - 使用 sed 批量重命名文件

标签 bash shell sed file-rename

目标

更改这些文件名:

  • F00001-0708-RG-biasliuyda
  • F00001-0708-CS-akgdlaul
  • F00001-0708-VF-hioulgigl

这些文件名:

  • F0001-0708-RG-biasliuyda
  • F0001-0708-CS-akgdlaul
  • F0001-0708-VF-hioulgigl

shell 代码

测试:

ls F00001-0708-*|sed 's/\(.\).\(.*\)/mv & \1\2/'

执行:

ls F00001-0708-*|sed 's/\(.\).\(.*\)/mv & \1\2/' | sh

我的问题

我不明白 sed 代码。我明白什么是替代品 命令

$ sed 's/something/mv'

意味着。我对正则表达式有些了解。但我不 了解这里发生了什么:

\(.\).\(.*\)

或在这里:

& \1\2/

前者,对我来说,只是看起来意味着:“单个字符, 后跟单个字符,后跟任意长度的 a 序列 单个字符”——但肯定不止于此。至于 后半部分:

& \1\2/

我不知道。

最佳答案

首先,我要说最简单的方法是使用 预命名或重命名命令。

在 Ubuntu、OSX(Homebrew 包 rename、MacPorts 包 p5-file-rename)或其他带有 perl 重命名(prename)的系统上:

rename s/0000/000/ F0000*

或在使用 util-linux-ng 重命名的系统上,例如 RHEL:

rename 0000 000 F0000*

这比等效的 sed 命令更容易理解。

但是对于理解 sed 命令,sed 联机帮助页很有帮助。如果 您运行 man sed 并搜索 &(使用/命令搜索), 你会发现它是 s/foo/bar/替换中的一个特殊字符。

  s/regexp/replacement/
         Attempt  to match regexp against the pattern space.  If success‐
         ful,  replace  that  portion  matched  with  replacement.    The
         replacement may contain the special character & to refer to that
         portion of the pattern space  which  matched,  and  the  special
         escapes  \1  through  \9  to refer to the corresponding matching
         sub-expressions in the regexp.

因此,\(.\)匹配第一个字符,可以用\1引用。 然后 . 匹配下一个字符,该字符始终为 0。 然后\(.*\)匹配剩下的文件名,可以被\2引用。

替换字符串使用 &(原始字符串 filename) 和 \1\2 这是文件名的每个部分,除了第二个 字符,这是一个 0。

恕我直言,这是一种非常神秘的方式。如果为了 由于某些原因重命名命令不可用而您想使用 sed 来重命名(或者你做的事情太复杂了 为了重命名?),在你的正则表达式中更明确会使得它更 更具可读性。也许是这样的:

ls F00001-0708-*|sed 's/F0000\(.*\)/mv & F000\1/' | sh

能够看到实际发生的变化 s/search/replacement/使其更具可读性。也不会保留 如果你不小心运行它,从你的文件名中吸取字符 两次左右。

关于bash - 使用 sed 批量重命名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33293935/

相关文章:

regex - Linux CLI 更改价格(awk 还是 sed?)

linux - 如何遍历两组数据?

bash - sed:删除除最后 n 个字符之外的所有字符

c++ - 在 osx 上将已安装的卷识别为 CD/DVD

linux - 在文件夹中的 gzip 文件中查找字符串

c++ - 无法在 Bash for Windows 中通过管道输出

javascript - PHP 在 HTML 中显示实时 Shell 输出

linux - 如何使用case语句调用函数?

linux - bash + bash 脚本有类似 log4j 的东西吗?

bash - 用 shell 脚本处理文本文件(超过 10K 行)真的很慢吗?