【问题标题】:recursively rename largest txt file in each directory using find command, Test Case Code included使用 find 命令递归重命名每个目录中最大的 txt 文件,包括测试用例代码
【发布时间】:2021-04-13 03:50:42
【问题描述】:

我想要完成的是将每个目录中最大文件大小的 .txt 文件重命名为 keep.txt

您可以运行以下代码块来设置测试用例:

mkdir -p './file test/1 first'
mkdir -p './file test/2 second yay'
echo 'other file' > './file test/1 first/1other file.nfo'
echo 'smallest file' > './file test/1 first/1smallest file.txt'
echo 'this is a medium sized file' > './file test/1 first/1medium file.txt'
echo 'this is the very largest file of all the files' > './file test/1 first/1keep largest file.txt'
echo 'other file in the folder thats even larger than everything' > './file test/2 second yay/2other file.nfo'
echo 'smallest file' > './file test/2 second yay/2smallest file.txt'
echo 'this is the very largest file of all the files' > './file test/2 second yay/2keep largest file.txt'
cd 'file test'

输出应如下所示:

tree -L 9
.
├── 1 first
│   ├── 1keep largest file.txt
│   ├── 1medium file.txt
│   ├── 1other file.nfo
│   └── 1smallest file.txt
└── 2 second yay
    ├── 2keep largest file.txt
    ├── 2other file.nfo
    └── 2smallest file.txt

我整理的这个命令似乎只返回最大的 txt 文件,但它多次执行,这似乎是问题的一部分:

find . -type f -execdir sh -c 'ls -S1 -d "$PWD/"* | grep txt | head -n 1' \;

这是我重命名的想法,但它没有达到我的预期,我不知道为什么:

find . -type f -execdir sh -c 'ls -S1 -d "$PWD/"* | grep txt | head -n 1 | mv "{}" keep.txt' \;

【问题讨论】:

    标签: linux shell find rename


    【解决方案1】:

    目前,您正在为找到的每个文件执行 execdir 命令。

    另一种方法是使用 find 的 printf 标志并仅打印文件的大小和路径/名称,在仅打印最大文件的移动命令并将命令传送到 sh 执行之前对输出进行排序。

    find . -name "*.txt" -printf '%s,%f,%h\n' | sort -n | awk -F, '{ fil=$2;dir=$3 } END { print "mv \""dir"/"fil"\" \""dir"/folder.jpg\"" }'
    

    我们通过管道进行排序以使最大的文件位于输出的底部,然后我们通过管道进入 awk 以获取最后一条记录,从而构建实际的 mv 命令。

    一旦您确认 mv 命令符合预期,通过管道传递到 sh 等来执行它:

    find . -name "*.txt" -printf '%s,%f,%h\n' | sort -n | awk -F, '{ fil=$2;dir=$3 } END { print "mv \""dir"/"fil"\" \""dir"/folder.jpg\"" }' | sh
    

    要对每个目录执行解决方案,请运行:

    while read line;do find "$line" -name "*.txt" -printf '%s,%f,%h\n' | sort -n | awk -F, '{ fil=$2;dir=$3 } END { print "mv \""dir"/"fil"\" \""dir"/folder.jpg\"" }' | sh;done <<< "$(find . -type d)"
    

    【讨论】:

    • 我已经修改了解决方案,因为原来没有打印前导目录 %h
    • 我在源和目标周围添加了引号
    • 别担心,我已经修改了
    • 我在 find 的输出中添加了关于循环的附加信息。 -type d 获取目录。
    • 在 find 的 printf 指令中相应更改分隔符。
    猜你喜欢
    • 2019-05-20
    • 2011-06-15
    • 2014-07-12
    • 2018-04-14
    • 2022-01-06
    • 1970-01-01
    • 2020-01-01
    • 2010-12-13
    相关资源
    最近更新 更多