如何在循环中进行grep排除?

时间:2018-07-18 01:38:31

标签: linux bash shell sh

我有一个NPM_RESERVED_SCOPE,其中包含一个用逗号分隔的禁止范围列表。

我有一个NPM_ALLOWED_DEV_DEPENDENCIES_PACKAGES,其中包含用逗号分隔的异常列表。

NPM_RESERVED_SCOPE=@privatescope,@secondary
NPM_ALLOWED_DEV_DEPENDENCIES_PACKAGES="@privatescope/private-project-scripts,@privatescope/private-project-ci-build,@privatescope/private-project-ci-test,@privatescope/private-project-ci-release,@privatescope/private-project-ci-deploy,@privatescope/private-project-ci-release-transitive"


for i in $(echo ${NPM_RESERVED_SCOPES} | sed "s/,/ /g")
  do
    for j in $(echo ${NPM_ALLOWED_DEV_DEPENDENCIES_PACKAGES} | sed "s/,/ /g")
    do
      if [[ $(cat package.json | jq .devDependencies | grep "$i/" | grep -v "$j") ]]; then
        echo "[Error] GitHub release abort. Reason: devDependencies within scope $i are forbidden."
        exit 1
      fi
    done
  done

如果devDependencies除了异常列表之外不包含任何NPM_RESERVED_SCOPES,我希望通过此脚本。

这是文件package.json

{
  "devDependencies": {
     "@privatescope/private-project-ci-build": "^1.0.5",
     "@privatescope/private-project-ci-deploy": "^1.0.7",
     "@privatescope/private-project-ci-release": "^1.0.5",
     "@privatescope/private-project-release-transitive": "^1.0.6",
     "@privatescope/private-project-test": "^1.0.4",
     "@privatescope/private-project": "^0.15.22"
   }
}

我该怎么办?

1 个答案:

答案 0 :(得分:1)

通过将,替换为|并将列表包装在@(...)中,将列表转换为扩展模式。

reserved="@(${NPM_RESERVED_SCOPE//,/|})"
allowed="@(${NPM_ALLOWED_DEV_DEPENDENCIES_PACKAGES//,/|})"

现在,模式匹配可以替换嵌套的for循环。a = @(x|y|z)如果a匹配模式xyz中的任何一个。 / p>

while IFS= read -r dep; do
  if [[ $dep = $reserved && $dep != $allowed ]]; then
      echo "[Error] GitHub release abort. Reason: $dep within scope $i is forbidden." >&2
      exit 1
  fi
done < <( jq .devDependencies '.devDependencies' )