Anonymous Anonymous - 3 years ago 191
Bash Question

Grep user input to find number

I have a File which looks like this

example text [1234] [0] Part 2 /var/tmp/path
example text [1234] [0] Part 3 /var/tmp/path
example text [1234] [0] Some Text more text
example text [1235] [0] Part 4 /var/tmp/path
example text [1235] [0] Part 5 /var/tmp/path
example text [1236] [0] Part 6 /var/tmp/path
example text [1236] [0] other text foo bar

I have another text file where users can write the parts in.
So it can look like this:

Part 2
Part 4
Part 6

I need a grep or so the second file gets read and it searched for the numbers in the first bracket, and saves them into an variable

In the example I'd need to get the output


And it should be in a variable to use it for further work

So far I tried it with

grep -F -f parts.txt search.log

But I don't know how to not get the line where Part 2, 4 and 6 are shown, but only the number within the first brackets

Answer Source

Here is one way to do it.

myparts=$(grep -F -f parts.txt search.log | awk -F'[][]' '{print $2}' | sort | uniq)

parts.txt is the file that users write part numbers in.

grep returns the lines where part number matches. awk uses [ and ] as delimiters to extract the first word between them

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download