【问题标题】:Having trouble arranging files into directories将文件排列到目录中时遇到问题
【发布时间】:2019-04-04 19:06:38
【问题描述】:

我正在尝试将名称为 f##.txt(#作为数字 0-9)的文本文件组织到目录中,以使它们最终成为 d#/f#.txt。

#! /bin/bash                                                                                                                                                                                                

for i in {0..9} ;
do
    mkdir -p "$1/d$i "
    for j in {0..9};
    do
    FILE= "/$1/f$i$j.txt"
        if [ -f FILE ];
        then
            echo 'Moving!'
            mv "/$1/f$i$j.txt" "/$1/d$i/f$j.txt"
        fi
    done
done

上面的代码是我到目前为止的代码,但我不断收到错误:

CO1101/OSN2/q4-arrange.sh: line 8: /test/f00.txt: No such file or directory

我不知道哪里出错了。

测试目录在当前工作目录中

【问题讨论】:

  • 是否存在目录/test? IE。 root中的目录test

标签: linux bash


【解决方案1】:

您在 FILE= 和“/$1/f$i$j.txt”之间似乎有一个空格。尝试删除空间,看看会发生什么。 Bash 不喜欢变量赋值中的空格(即等号周围)。

希望这会有所帮助。

【讨论】:

  • 现在没有更多错误,但 if 语句似乎不起作用,文件 f48.txt 存在但没有移动。
  • 您只是在测试字符串 FILE,而不是为变量 FILE 分配的内容。
  • 应该是:if [ -f $FILE ];
  • 是的。您想验证 FILE 变量中定义的文件是否存在。就像你的 i 和 j 变量一样。
【解决方案2】:

你可以试试这样的:

#!/usr/bin/env bash

pref=f ext=txt
for f in "$pref"[0-9][0-9]."$ext"; do
    num=${f#"$pref"} num=${num%."$ext"}
    dir=d${num%?} file=$pref${num#?}.$ext

    [[ -d $dir ]] || mkdir -- "$dir" || exit 1
    mv -- "$f" "$dir/$file"
done

测试运行:

$ tree
.
├── f11.txt
├── f14.txt
├── f28.txt
├── f30.txt
└── script
$ ./script
$ tree
.
├── d1
│   ├── f1.txt
│   └── f4.txt
├── d2
│   └── f8.txt
├── d3
│   └── f0.txt
└── script

【讨论】:

    【解决方案3】:

    如果您有 rename 实用程序 - 也称为 Perl 重命名,您可以使用这个相当简洁的命令:

    rename --dry-run -p 's|f([0-9])([0-9])|d$1/f$2|' *txt
    

    样本输出

    'f11.txt' would be renamed to 'd1/f1.txt'
    'f14.txt' would be renamed to 'd1/f4.txt'
    'f28.txt' would be renamed to 'd2/f8.txt'
    'f30.txt' would be renamed to 'd3/f0.txt'
    

    请参阅 cmets here 了解如何在各种发行版中调用该包。


    如果有人使用 ma​​cOS,您可以使用 homebrew 安装它:

    brew install rename
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多