【问题标题】:How do you create directories based on filenames and move identically-named files (different formats) into them?如何根据文件名创建目录并将同名文件(不同格式)移动到其中?
【发布时间】:2021-11-19 14:18:28
【问题描述】:

我有一个不同格式的文件列表,所有文件在同一目录中都具有相同的名称(即 file1.txt、file1.conf、file2.txt、file2.conf 等)。我要做的是根据文件名创建目录,然后将所有相应的文件移动到新创建的目录中。

我在 Stack Overflow 中发现了几个与切线相关的问题,我试图将它们汇总在一起:

#!/bin/bash
for f in ./*.txt ./*.conf ; do
  [[ -e "$f" ]] 
  dir="${f%.*}"
  if [ ! -d "$dir" ] ; then
  mkdir "$dir"
  fi
  mv "$f".* "$dir"

done

诚然,我是在 shell 中工作的新手,所以我还不完全理解参数化。我认为在for 循环中我会使用-e 标志来检查.txt 或.conf 文件是否存在,文件名被分配给$f,创建一个名为$f 的目录它还没有存在,然后将所有名为 $f 的文件移动到目录中。

【问题讨论】:

  • 您可以使用./*.* 对每个带有扩展名的文件执行此操作。否则,我会明确指定要定位的所有扩展。无论哪种方式,使用mv "$f" "$dir"(不是"$f".*),使用[[ -e "$f" ]] || continue,并且您还真的需要检查$dir 不是现有文件,否则您将覆盖它。

标签: bash shell


【解决方案1】:

我认为是这样的。

#!/bin/sh

for file in ./*.txt ./*.conf; do
    basename="${file##*/}" # Remove the path e.g. ./file.txt ==> file.txt
    targetDir="${basename%.*}" # Remove the extension e.g. file.txt ==> file
    mkdir -p "$targetDir" # Create a new directory if not exist. Ignore otherwise.
    echo mv "$file" "$targetDir" # Move file to the target directory.
done

要完成这项工作,请删除最后一个 echo

【讨论】:

  • 感谢分享!我认为它实际上是在尝试移动./*txt,因为我收到以下错误:mv: cannot stat './*.txt': No such file or directory mv: cannot stat './*.conf': No such file or directory 我尝试回显其他行,并认为 targetDir 没有被分配,可能是因为它将 *.txt 视为文字?这会弹出 txt 和 conf 文件(我使用 || 来识别新行):basename=*.txt || targetDir= || mkdir -p || mv *.txt
  • 这意味着,您进入了错误的目录。首先cd到包含文件的目录,然后使用ls进行验证。如果您看到 *.txt 和 *.conf,那么您位于正确的目录中。首先运行脚本而不删除echo,在您确定输出正确之后,然后您可以删除该echo。确保脚本也在同一目录中。
  • 谢谢!你介意解释一下特殊字符的作用吗?我知道 $ 标识了一个变量,但不知道大括号如何确定文件的基本名称和 &.* 去掉文件扩展名。根据我正在阅读的内容 {} 构建了一个数组,但该数组是否仅包含它找到的每个 .txt/.conf 文件?最后两行对我来说很有意义。
  • 我这里没有使用数组。这都是关于参数扩展。你了解更多here
猜你喜欢
  • 1970-01-01
  • 2016-03-21
  • 2019-10-30
  • 2020-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 2018-09-20
相关资源
最近更新 更多