我必须处理大量嵌套在目录内的文件(每个目录一个文件),类似于以下内容:
fred/result.txt
john/result.txt
mary/result.txt
...
我目前正在使用以下命令来处理每个文件:
find . -maxdepth 1 -type d \( ! -name . \) -exec bash -c \"cd '{}' && processResult result.txt\" \;
我正在寻找可以添加到该命令末尾的内容,该文件名会将文件名更改为fred.txt
,等等,然后稍后将文件移至父目录以消除多余的目录层。
最好的方法是什么?
我们可以使用经典方法:find
与while read
组合:
演示:
$ ls *
fred:
results.txt
jane:
results.txt
john:
results.txt
$> find . -type f -name "results.txt" -printf "/%P\n" | while read FILE ; do DIR=$(dirname "$FILE" );\
> mv ."$FILE" ."$DIR""$DIR".txt;done
$> ls
fred/ jane/ john/
$> ls *
fred:
fred.txt
jane:
jane.txt
john:
john.txt
使用echo
使用前mv
要测试你的文件就行了。
小改进
我们可以bash
使用参数扩展(特别是前缀删除)将对的调用嵌入到exec中。基本上,它是将脚本嵌入到exec调用中。
$> find "$PWD" -type f -name "results.txt" -exec bash -c ' DIR=$( dirname "{}" ); echo "{}" "$DIR"/"${DIR##*/}".txt ' \;
/home/xieerqi/TESTDIR/fred/results.txt /home/xieerqi/TESTDIR/fred/fred.txt
/home/xieerqi/TESTDIR/jane/results.txt /home/xieerqi/TESTDIR/jane/jane.txt
/home/xieerqi/TESTDIR/john/results.txt /home/xieerqi/TESTDIR/john/john.txt
要使该命令具有通用性((可用于任何文件,而不仅限于results.txt
)),只需删除-name "results.txt"
一部分即可。另请参阅这篇文章,以获取替代的Python解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句