Bashで複数行の文字列を検索する

Bashで複数行の文字列を検索する

現在Jupyter Notebookを使用しています。 IDEを使用して別の場所にある可能性のあるコード部分を見つけ、必要に応じてリファクタリングすることができました。

次のコードがあるとしましょう。

 class.function('--parameter','-p', type = lambda x: operation(x,"%Y-%m-%d").date(),
                    default=unicode(previousTime-actualTime),
                    help='Send help'
                    )

コードは編集されており、機能することを意図したものではありません。複数行、複数の「奇妙な」文字、引用符などがある可能性の例を提供したかったです。

今、私のコードベースに正しい文字列が存在することを確認したいと思います。

ここでそこを見て、マニュアルを読んでみましたが、次のような内容があります。

 grep -rxno . -e "string starts
more text here %% 'parameters inside quotes'
string ends"

しかし、正規表現なので、一致する部分文字列に似ていますが、必ずしも同じではないようです。また、より混乱しても、1行に結果を提供します。

./DMP3K/DMP_3K.py:30:class.function(
./DMP3K/DMP_3K.py:31:    
./DICC/diccionario.py:34:                        operation(x,"%Y-%m-%d").date()

私が逃したこのタスクを実行するより簡単な方法があるべきだと思います。

ベストアンサー1

grepGNU(Linuxのデフォルト)にアクセスできる場合は、-z次のコマンドを使用できます。

   -z, --null-data
          Treat  input  and output data as sequences of lines, each terminated by a
          zero byte (the ASCII NUL character) instead of a newline.  Like the -Z or
          --null  option,  this  option  can  be used with commands like sort -z to
          process arbitrary file names.

これにより、複数行にまたがるパターンを指定できます。次に、-F正規表現として解釈されないパターンを使用します。

   -F, --fixed-strings
          Interpret PATTERN  as  a  list  of  fixed  strings  (instead  of  regular
          expressions), separated by newlines, any of which is to be matched.

最後に、検索文字列を変数に保存します。

$ IFS='' read -r -d '' pat <<EoF
> class.function('--parameter','-p', type = lambda x: operation(x,"%Y-%m-%d").date(),
>                     default=unicode(previousTime-actualTime),
>                     help='Send help'
>                     )
> EoF

上記のコードを実行するには、まず端末に次のように書きます。

IFS='' read -r -d '' pat <<EoF

次に、探している行を貼り付けますEoF。検索文字列が新しい行で終わらない場合は、その行に含める必要があるため、書き込みEnter前にキーを押してください。EoF

これでgrep、ファイルを次のようにすることができます。

grep -z "$pat" /path.to/files/*

上記の意味は

おすすめ記事