bash - 在查找命令行上插入排除项
问题描述
我遇到了一个有趣的问题。
我有一个查找特定内容的应用程序。它将从其命令行获取内容作为排除列表。这是一个快速的代码破解来演示这个问题:
#! /usr/bin/env bash
gen.exclude () {
local i
for i in "$@" ; do
echo -n "-not -path *${i}* "
done
}
run.find () {
echo find . $(gen.exclude "$@") -print
find . $(gen.exclude "$@") -print
}
rm -rf a
rm -rf b
mkdir a
mkdir b
echo "file 1a" >a/file1
echo "file 2a" >a/file2
echo "file 3a" >a/file3
echo "file 1b" >b/file1
echo "file 2b" >b/file2
echo "file 3b" >b/file3
cp -r "a" "b/a"
run.find '/a/' # fails because of wild card expansion
在此示例中,为/a/到 -not -path */a/* 创建了一个排除项。不幸的是,这会将通配符扩展为多个字符串并导致 find 出错。
我可以将排除项括在引号中,但随后它们会被视为排除字符串的一部分,这使它成为一个 noop。
有没有办法做到这一点?
解决方案
不要gen.exlude
分开run.exclude
; 在run.exclude
.
run.exclude () {
local -a exclusions
for i in "$@"; do
exclusions+=( -not -path "*$i*" )
done
echo "find . ${exclusions[*]} -print"
find . "${exclusions[@]}" -print
}
对于某些参数,您记录的内容看起来与实际运行的内容不同,但您运行的内容将是正确的。
推荐阅读
- spartacus-storefront - 如何在 Spartacus 版本 4 中使用 Web 服务设置身份验证配置?
- python - 可以在脚本中操作的 DataFrame 的数量是否有限制?
- javascript - 如何在 JavaScript 中使用 CSS 过渡?
- python - 从 anaconda 基础环境中删除 pip 包
- reactjs - 如何从 React 客户端代理到 Springboot 服务器
- pip - 无法为全新的 Python 3.2 安装安装 Pip“没有为 pip<8 找到匹配的发行版”
- php - 为什么创建合并的命名空间而不是子模块?
- html - 使用 itext7 时 html 到 pdf 转换的问题
- javascript - JavaScript ClearInterval 按钮不会停止
- java - 我正在尝试使用 API 请求从 Web cite 中删除特定模块,但它会删除一个随机模块