我有一个input.txt文件,其中的行表示一些命令,每个命令都有两个输入参数:
commands a b
commands a c
commands b c
...我希望删除文件夹out中有匹配(输出文件)的所有行。例如,假设只有out/a_b_out和out/b_c_out文件存在。然后,我想从input.txt中删除第一行和第三行。
此外,out中可能有数以百万计的文件,所以我需要一种有效的方法来查找匹配。另一方面,input中的行数约为数千行,更易于管理。
我首先尝试从输入文件(例如cut -d " " -f 2-3 input.txt | sed -e 's/\ /_/g')中提取模式,然后遍历这些条目并使用grep等。
我想知道是否有一种更快、更优雅的方式来实现这一点。谢谢!
发布于 2017-03-15 01:56:53
这可能对你的案子有用
while read c x y;
do [ -f "out/${x}_${y}_out" ] || echo "$c" "$x" "$y"
done < input将迭代较短的输入文件,并根据现有文件筛选行;输出将是未找到文件的命令。如果您的输入文件格式不佳,则可能需要加强read命令。
发布于 2017-03-15 01:54:07
请看这个使用awk的小测试(如果awk在游戏中),它做的正好相反(只是为了测试):
$ cat file3
commands a b
commands a c
commands b c
$ ls -l *_out
-rw-r--r-- 1 root root 0 Mar 15 04:02 a_b_out
-rw-r--r-- 1 root root 0 Mar 15 04:05 b_c_out
$ awk 'NR==FNR{a[$2 "_" $3 "_out"]=$0;next}($0 in a){print a[$0]}' file3 <(find . -maxdepth 1 -type f -printf %f\\n)
commands b c
commands a b 这意味着这个倒排的命令应该给出您需要的结果:
$ awk 'NR==FNR{a[$2 "_" $3 "_out"]=$0;next}(!($0 in a)){print a[$0]}' inuutfile <(find . -maxdepth 1 -type f -printf %f\\n) >newfile您可以删除can深度1以进入所有子目录。
此解决方案基于小输入文件构建索引,而不是基于可能存在于out中的数百万个文件;因此,期望性能足够好。
将非匹配结果发送到新文件将比持续重写现有文件要快得多。
完成后可以将新文件移到旧文件上(mv newfile inputfile)
https://stackoverflow.com/questions/42799522
复制相似问题