首页 > 解决方案 > 是否可以使用数组作为模式进行grep?

问题描述

TL;DR 如何使用 grep 过滤 ls/find 输出,并将数组作为模式?

背景故事:我有一个管道,我必须为遇到错误的数据集重新运行它。哪些数据集遇到错误保存在制表符分隔的文件中。我想删除管道遇到错误的文件。

为此,我从另一个包含已完成数据集的文件中提取数据集名称并将它们保存在 bash 数组 {ds1 ds2 ...} 但现在我被卡住了,因为我无法弄清楚如何从删除中排除数组中的数据集步。

这是文件夹结构(X=1-30):datasets/dsX/results/dsX.tsv

不排除完成的数据集,这意味着删除失败的文件夹和完成的数据集就像一个魅力

#1. move content to a trash folder
ls /datasets/*/results/*|xargs -I '{}' mv '{}' ./trash/

#2. delete the empty folders
find /datasets/*/. -type d -empty -delete

但由于我想排除完成的数据集,我认为将它们保存在数组中会很聪明:

#find finished datasets by extracting the dataset names from a tab separated log file
mapfile -t -s 1 finished < <(awk '{print $2}' $path/$log_pf)
echo ${finished[@]}

它按预期工作,但现在我被困在使用该数组过滤 ls 输出:*pseudocode

#trying to ignore the dataset in the array - not working
ls -I${finished[@]} -d /datasets/*/
#trying to reverse grep for the finished datasets - not working
ls /datasets/*/ | grep -v {finished}

您如何看待我目前的想法?这可能只使用 bash 吗?我想在 python 中我可以很容易地做到这一点,但出于培训目的,我想在 bash 中做到这一点。

标签: bashgrep

解决方案


grep-f可以使用该选项从文件中获取模式。请注意,包含换行符的文件名会导致问题。

如果您需要以某种方式处理输入,可以使用进程替换:

grep -f <(process the input...)

推荐阅读