简体   繁体   中英

How do I grep multiple lines (output from another command) at the same time?

I have a Linux driver running in the background that is able to return the current system data/stats. I view the data by running a console utility (let's call it dump-data ) in a console. All data is dumped every time I run dump-data . The output of the utility is like below

Output:
- A=reading1
- B=reading2
- C=reading3
- D=reading4
- E=reading5
...
- variableX=readingX
...

The list of readings returned by the utility can be really long. Depending on the scenario, certain readings would be useful while everything else would be useless.

I need a way to grep only the useful readings whose names might have have nothing in common (via a bash script). Ie Sometimes I'll need to collect A,D,E; and other times I'll need C,D,E.

I'm attempting to graph the readings over time to look for trends, so I can't run something like this:

# forgive my pseudocode
Loop
    dump-data | grep A
    dump-data | grep D
    dump-data | grep E
End Loop

to collect A,D,E as that would actually give me readings from 3 separate calls of dump-data as that would not be accurate.

If you want to save all result of grep in the same file, you can just join all expressions in one:

grep -E 'expr1|expr2|expr3'

But if you want to have results (for expr1, expr2 and expr3) in separate files, things are getting more interesting.

You can do this using tee >(command) .

For example, here I process the same pipe with thre different commands:

$ echo abc | tee >(sed s/a/_a_/ > file1) | tee >(sed s/b/_b_/ > file2) | sed s/c/_c_/ > file3
$ grep "" file[123]
file1:_a_bc
file2:a_b_c
file3:ab_c_

But the command seems to be too complex.

I would better save dump-data results to a file and then grep it.

TEMP=$(mktemp /tmp/dump-data-XXXXXXXX)
dump-data > ${TEMP}
grep A ${TEMP}
grep B ${TEMP}
grep C ${TEMP}

You can use dump-data | grep -E "A|D|E" dump-data | grep -E "A|D|E" . Note the -E option of grep. Alternatively you could use egrep without the -E option.

你可以简单地使用:

dump-data | grep -E 'A|D|E'
awk '/MY PATTERN/{print > "matches-"FILENAME;}' myfile{1,3}

堆栈交换中的 大师

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM