検索と変数に関する問題

検索と変数に関する問題

次のさまざまなバリエーションを試しましたが、何も機能しないようです。基本的にfind実行しても何も起こらないようです。以下に、bash関数コードとそれを実行したときの出力を示します。

以下のコードで何が起こるのか、コマンドを明示的に入力したときとは異なる動作をする理由が何であるかを知りたいです。

また、私が作業するいくつかのボックスにアクセスできないと言われたrgrepので、grepコードなどの一般的な解決策を得るためにこの方法を使用しようとしています。

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]}
}

出力は次のとおりです

$ 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'

ベストアンサー1

おそらく使用しようとしていたパターンはありますが、使用したいパターンには、ファイルと*.txt一致しない一重引用符が含まれています。拡張は次のように機能します。find -name'*.txt'

コマンドラインから、入力すると

$ find -name '*.txt'

シェルは引用'*.txt'符を見て、引用符を削除して内容*.txtをに渡しますfind

機能上

find -name "'$var'"

シェルは$varに展開されます*.txt。拡張は二重引用符内で発生するため、シェルは二重引用符を削除して内容を'*.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 "$@"
}     

おすすめ記事