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

질문에서 답변으로 이동

나는이 해결책을 생각해 냈습니다. 우아하고 짧지는 않지만(또한 하나의 이벤트만 발견되었다고 가정하지만 확장 가능) 작업을 완료합니다.

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

관련 정보