【问题标题】:Delete some entries of a list or array in bash在 bash 中删除列表或数组的一些条目
【发布时间】:2019-04-09 23:58:09
【问题描述】:

我想将 Python 的一个函数应用于给定目录的子目录中的所有文件。

在 bash,.sh 文件中,我列出了所有文件,如下所示:

dir_list=()
while IFS= read -d $'\0' -r file ; do
dir_list=("${dir_list[@]}" "$file")
done < <(find give_directory_Here -mindepth 2 -maxdepth 2 -type d -print0)

但是,有一些目录具有模式,假设模式是 unwanted_pattern,我想从 dir_list 中删除它们的名称。

我该怎么做?

我在这里尝试了一些对我不起作用的东西: solution 1 from stack over flow 或者 solution 2 from stack exchange,以此类推!

【问题讨论】:

  • 第一行提到了Python,但是在这里我没有看到其他关于Python的内容,意思也不清楚。如果您只是将其编辑掉,它会一样准确吗?

标签: arrays bash list command-line remove-if


【解决方案1】:

在 bash 中删除列表或数组的一些条目

只需循环和匹配:

   result=()
   for file in "${dir_list[@]}"
   do
     if [[ "$file" != *"unwanted_pattern"* ]]
     then
       result+=("$file")
     fi
   done
   dir_list=( "${result[@]}" )

但是,这是您的XY question 的答案,而不是您应该做的事情。

更聪明的方法是不首先添加它们,而是在循环中添加这样的检查,更聪明的方法是让find 排除它们:

find give_directory_Here -mindepth 2 -maxdepth 2 -type d ! -path '*unwanted_pattern*' -print0

【讨论】:

  • 非常感谢,关于 XY 的事情,如果我没有这样做,人们会说“你尝试了什么?”,“它不可重现”等 :) 而且,最重要的是,现在我通过 1 个问题学到了两件事:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 2014-05-14
  • 2011-12-20
相关资源
最近更新 更多