重命名文件,使用 text-file 作为来源

Rename files, using text-file as source

在一个文件夹中,我有600个文件,编号从001到600。看起来像foo_001.bar。在一个文本文件中,我有这个文件夹的编号和标题。现在我想用文本文件中相应的 001 标题 foobar 重命名 foo_001.bar。

但我不知道如何在 Linux Mint 上正确执行此操作。有人可以帮助我或给我提示吗?

titles.txt 的内容如下所示。在数字和标题之间有一个标签(当然可以很容易地改变)。

001 title of 1
002 this is 2
003 and here goes 3
004 number four
005 hi this is five
etc

文件夹的内容如下所示。没有例外。

file_001.ext
file_002.ext
file_003.ext
file_004.ext
file_005.ext
etc

只需使用 read 遍历您的文件,使用 awk cut 获取分隔的列(谢谢,@Jack)和mv 您的文件相应。在这个非常简单的实现中,我假设您的包含新名称的文本文件位于 ./filenames 并且您的脚本是从包含您的文件的目录中调用的。

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
        NR=$(echo "$line" | cut -f 1)
        NAME=$(echo "$line" | cut -f 2)
        if [ -f "foo_${NR}.ext" ] ; then
                mv "foo_${NR}.ext" "$NAME"
        fi
done < filenames