grep -nrを使ってファイルとライン出力に移動するには?

grep -nrを使ってファイルとライン出力に移動するには?

走ると仮定しよう grep -nr . -e "This text was found"

CLIと入力します。 ./subfolder/file.ext:10 This text was found

つまり、「subfolder」フォルダにある「file.ext」ファイルの10行目です。

この識別子 "./subfolder/file.ext:10" を使用して、このファイルの行をどのように出力できますか?それとも別のフォルダへのパスに切り替えますか?

たとえば、私はそこに飛び込み、CLIで次のことを見ました。

$otherfolder/subfolder/file.ext:10 Another text here

ベストアンサー1

質問から回答に移動

私はこの解決策を思いついた。エレガントで短くはありませんが(もう1つのイベントしか見つからないと仮定しますが、スケーラブルです)作業を完了します。

res=$(grep -nr . -e 'This text was found')
num=$(echo $res | cut -d: -f2)            # extract the number
file=$(echo $res | cut -d: -f2)           # extract the filename
sed -n "${num}p" $file                    # jump to the found line in the found file
folder=$(echo $file | cut -d/ -f1)
subpath=$(echo $file | cut -d/ -f1-)
sed -n "${num}p" $otherfolder/$subpath    # jump to the same line and subfolder structure in the other folder

おすすめ記事