【问题标题】:Renaming Files By Adding Numbers Prefixes In File Names通过在文件名中添加数字前缀来重命名文件
【发布时间】:2021-04-02 21:02:31
【问题描述】:

我有一个带有数字前缀的文件列表,例如 1-filename.txt 2-filename.txt ..so on 。我发现我跳过了一个文件名 45-filename.txt 。我在那个目录中有从1-filename.txt100-filename.txt 的文件。现在我想通过创建一个 bash 脚本重新排列所有带有数字前缀的文件而不会丢失它们的实际名称(例如 filename.txt),但没有这样做。我创建的脚本如下。

#!/bin/bash

n=1
for i in *.txt;
do
        file=$(ls -v "$i"  | awk -F- ' { print $NF }')
        mv  $i "$n-${file}"
        let n=n+1
done

但我没有得到所需的输出。

注意文件名称中有空格,例如:1-my first file.txt 2-my second file.txt ....等等。

【问题讨论】:

  • ls -v "$i" ?只是echo "$i"note files have spaces in its name 然后引用它。 mv "$i"
  • 不清楚您要达到的目标。从你的代码来看,你每次都用 mv 命令覆盖一个文件,因为 n 永远不会改变?
  • 第一let n=n+1
  • 只需将 100-filename.txt 移动到 45-filename.txt?
  • @RamanSailopal 我正在尝试通过删除以前的数字前缀并再次添加相同的前缀来重写他们的文件名,因为错误地跳过了一个数字。

标签: bash shell file-rename file-manipulation


【解决方案1】:

我会使用一个数组来存储当前文件名“tail”,由文件名前缀编号索引:

files=()
for file in *-*.txt; do
    n=${file%%-*}    # everthing before the first "-"
    name=${file#*-}  # everthing after the first "-"
    files[n]=$name
done

遍历数组索引 occurs in numerical order:

c=0
for n in "${!files[@]}"; do
    if (( n != ++c )); then
        echo mv "${n}-${files[n]}" "${c}-${files[n]}"
    fi
done

演示:

$ touch 1-abc.txt 2-def.txt 3-ghi.txt 8-foo.txt 12-bar.txt 100-baz.txt

$ for file in *-*.txt; do
>     n=${file%%-*}    # everthing before the first "-"
>     name=${file#*-}  # everthing after the first "-"
>     files[n]=$name
> done

$ declare -p files
declare -a files=([1]="abc.txt" [2]="def.txt" [3]="ghi.txt" [8]="foo.txt" [12]="bar.txt" [100]="baz.txt")

$ c=0

$ for n in "${!files[@]}"; do
>     if (( n != ++c )); then
>         echo mv "${n}-${files[n]}" "${c}-${files[n]}"
>     fi
> done
mv 8-foo.txt 4-foo.txt
mv 12-bar.txt 5-bar.txt
mv 100-baz.txt 6-baz.txt

如果您觉得echo 看起来不错,请删除它。

【讨论】:

  • 这不处理具有相同数字前缀的 2 个文件:只有最后一个(按字母顺序)存储在数组中。
猜你喜欢
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 2021-09-08
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多