【问题标题】:How to find and move all files matching given Beginning Of File (BOF) string?如何查找和移动与给定文件开头(BOF)字符串匹配的所有文件?
【发布时间】:2020-12-17 16:54:33
【问题描述】:

如何通过命令行将所有以foo开头的文件移动到另一个文件夹?

我尝试在匹配时回显文件名:

for f in *.txt; do if [ $(head -c5 $f) = "foo" ]; then echo $f; fi; done;

但我经常收到此错误:

-bash: [: too much arguments

【问题讨论】:

标签: bash


【解决方案1】:

将 Perl 单行代码与 find 和 xargs 结合使用,如下所示:

echo foo > 1.txt
echo "foo\nbar" > 2.txt
echo "bar\nfoo" > 3.txt
mkdir foodir
find .  -maxdepth 1 -name '[123].txt' -exec perl -lne 'print $ARGV if /^foo/; last;' {} \; | xargs -I{} mv {} foodir 
find foodir -type f
# foodir/2.txt
# foodir/1.txt

【讨论】:

  • 谢谢,不过我终于修复了:for f in *.txt; do if [ "`head -c5 $f`" = "foo" ]; then mv $f ../tmp2/; fi; done;
【解决方案2】:

用 awk 查找

find . -type f -exec awk -F \/ "NR < 6 && /foo/ { fnd=1 } END { if (fnd==1) { split(FILENAME,arr,\"/\");print \"mv -f \"FILENAME\" newdir/\"arr[length(arr)] } }" '{}' \;

使用 awk 处理前 5 行 (NR

find . -type f -exec awk -F \/ "NR < 6 && /foo/ { fnd=1 } END { if (fnd==1) { split(FILENAME,arr,\"/\");print \"mv -f \"FILENAME\" newdir/\"arr[length(arr)] } }" '{}' \; | bash

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 2021-08-30
    • 2010-10-22
    • 1970-01-01
    • 2014-10-20
    • 2015-02-17
    • 2020-03-25
    相关资源
    最近更新 更多