查找和变量的问题

xta*_*odi 2 bash

我尝试了以下不同的变体,但似乎没有任何效果。基本上当find被执行时似乎什么都没有发生。下面我展示了我的 bash 函数代码和运行时的输出。

我有兴趣了解下面的代码会发生什么,以及为什么它不像我明确键入命令时那样表现。

我还被告知我将无法访问rgrep我将要处理的某些盒子,因此我尝试使用这种方法来获取代码等的通用解决方案。

function findin() {

if [ -z $1 ] ; then

    echo "Usage: findin <file pattern> <<grep arguments>>"
    return 1

fi

fIn[1]=$1

shift
fIn[2]="$@"

echo -- "${fIn[1]}"
echo -- "'${fIn[2]}'"

find -type f -name "'${fIn[1]}'" -print0 | xargs -0 grep --color=auto ${fIn[2]}
}
Run Code Online (Sandbox Code Playgroud)

输出是:

$ ls
Server.tcl  Server.tcl~  test.cfg  vimLearning.txt
$ find -type f -name '*.txt' -print0 | xargs -0 grep --color=auto char
x      deletes char under cursor. NNx deletes NN chars to RHS of cursor.
r      type r and the next char you type will replace the char under the cursor.
$ findin '*.txt' char
-- *.txt
-- 'char'
Run Code Online (Sandbox Code Playgroud)

jw0*_*013 5

您可能打算使用的模式是*.txt,但您告诉find -name使用'*.txt',包括单引号,它与任何文件都不匹配。扩展工作如下:

在命令行上,当您键入

$ find -name '*.txt'
Run Code Online (Sandbox Code Playgroud)

你的外壳看到'*.txt'被引用,所以它去掉引号并将内容传递*.txtfind

在函数中

find -name "'$var'"
Run Code Online (Sandbox Code Playgroud)

外壳扩展$var*.txt. 由于扩展发生在双引号内,shell 去掉双引号并将内容传递'*.txt'find

解决方案很简单:删除find -name "'$var'".


我为你修改了你的功能:

findin () {
    if (( $# < 2 )); then
        >&2 echo "Usage: findin <file pattern> <grep arguments ...>"
        return 1    
    fi               
    pattern=$1               
    shift
    printf '%s\n' "-- ${pattern}"
    printf '%s ' "-- $@"
    echo
    find -type f -name "${pattern}" -print0 | 
            xargs -0 grep --color=auto "$@"
}     
Run Code Online (Sandbox Code Playgroud)