grep을 여러 매개변수 및 다양한 출력 스위치와 결합하는 방법

grep을 여러 매개변수 및 다양한 출력 스위치와 결합하는 방법

소스 파일에 나타나는 순서대로 한 매개변수 앞과 다른 매개변수 뒤에 행을 표시하려는 여러 매개변수를 사용하여 grep을 수행하고 싶습니다. 즉, 다음과 같은 조합이 필요합니다.

grep -A5 onestring foo.txt

그리고

grep -B5 otherstring foo.txt

이것이 어떻게 달성될 수 있습니까?

답변1

Bash, ksh 또는 zsh에서:

sort -gum <(grep -nA5 onestring foo.txt) <(grep -nB5 otherstring foo.txt)
# Sort by general numbers, make output unique and merge sorted files,
# where files are expanded as a result of shell's command expansion,
# FIFOs/FDs that gives the command's output

이를 위해서는 O(Ngrep) 시간, 출력이 정렬되었음을 고려합니다 . 프로세스 교체가 불가능한 경우 임시 파일을 수동으로 생성하거나 O(NLGN) ( grep -nA5 onestring foo.txt; grep -nB5 otherstring foo.txt ) | sort -gu.

grep -H좀 더 자세한 방법으로 정렬해야 합니다(cas에게 감사드립니다) .

# FIXME: I need to figure out how to deal with : in filenames then.
# Use : as separator, the first field using the default alphabetical sort, and
# 2nd field using general number sort.
sort -t: -f1,2g -um <(grep -nA5 onestring foo.txt bar.txt) <(grep -nB5 otherstring foo.txt bar.txt)

관련 정보