首页 > 解决方案 > 在查找命令行上插入排除项

问题描述

我遇到了一个有趣的问题。

我有一个查找特定内容的应用程序。它将从其命令行获取内容作为排除列表。这是一个快速的代码破解来演示这个问题:

#! /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。

有没有办法做到这一点?

标签: bash

解决方案


不要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
}

对于某些参数,您记录的内容看起来与实际运行的内容不同,但您运行的内容将是正确的。


推荐阅读