Como eu combino o grep com vários argumentos e diferentes comutadores de saída

2

Eu quero grep com vários argumentos em que quero mostrar as linhas na ordem em que aparecem no meu arquivo de origem antes de um argumento e linhas após o outro argumento, e eu combine:

grep -A5 onestring foo.txt

e

grep -B5 otherstring foo.txt

Como isso pode ser alcançado?

    
por kungjohan 25.10.2015 / 09:49

1 resposta

4

No bash, ksh ou 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

Isso leva o tempo O ( n ), dado que grep gera as coisas já classificadas. Se a substituição do processo estiver indisponível, crie arquivos temporários manualmente ou use o O ( n lg n ) ( grep -nA5 onestring foo.txt; grep -nB5 otherstring foo.txt ) | sort -gu .

Com grep -H , precisamos classificá-lo de maneira mais detalhada (graças ao 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)
    
por 25.10.2015 / 10:05