【问题标题】:Is there a nice way to move .txt files with a specific character in the file (not filename) to another directory?有没有一种好方法可以将文件中具有特定字符(不是文件名)的 .txt 文件移动到另一个目录?
【发布时间】:2021-04-30 17:36:54
【问题描述】:

在 Mac 上使用 bash,我正在尝试检查 .txt 文件的文件夹,并且任何包含项目符号 (•) anywhere 的文件,将这些 .txt 文件移动到新的文件夹/子目录。有什么建议吗?

【问题讨论】:

  • mv *•*.txt newdir 应该可以工作
  • @jordanm 在文件名中查找,而不是文件内容。

标签: bash macos


【解决方案1】:

grep 可用于检查文件中是否存在字符:

#!/bin/bash
for filename in ./a/*.txt; do
    if grep -q • "$filename"; then
        mv "$filename" ./b/
    fi
done

【讨论】:

  • $filename 应该被引用,否则这会破坏带有空格或 shell 元字符的文件名。
【解决方案2】:

如果 .txt 文件名中没有空格(感谢@jordanm,指出 out),您可以在一行中完成 - 您可以使用 grep 告诉您文件名 (-l) 包含一个模式 (-e) 并将它们移动到您的 new_directory:

mv $(grep -l old_directory/*.txt -e •) new_directory/

【讨论】:

  • 如果任何文件名包含空格,这将不起作用。
  • 太棒了!对于带空格的文件名:mv "$(grep -l old_directory/*.txt -e •)" new_directory/
  • @Andrey Moiseev,在命令的 $( ... ) 部分加上双引号对我不起作用......但我无法理解错误的原因。跨度>
  • mv "$(grep -l old_directory/*.txt -e •)" new_directory/ 中的引号将按设计工作,当仅找到 1 个文件并且该文件的名称中有空格时。当grep 返回 2 个文件时,路径/文件名将连接起来,带引号的命令将尝试移动 1 个名称类似于 "old_directory/firstfile.txt old_directory/secondfile.txt" 的文件。它将寻找一个包含空格的子目录:firstfile.txt old_directory。我认为不会在该目录中找到secondfile.txt
  • @WalterA,是的,现在我看到这是我在测试时观察到的行为。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
  • 2020-06-03
  • 1970-01-01
相关资源
最近更新 更多