acezcoder
acezcoder

Reputation: 3

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

1234
1235
1236 

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

Upvotes: 0

Views: 291

Answers (2)

ramana_k
ramana_k

Reputation: 1933

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

Upvotes: 1

Maddy
Maddy

Reputation: 123

Not sure if only a single grep statement can do that work but a small loop can.

cat file2 |while read line
do
   grep $line file1|awk '{print $3}'|sed 's/\[//g'|sed 's/\]//g' >> tempfile
done

Now the tempfile can be used further or instead of temp file you can put that in a variable by

abcd="$abcd (grep $line file1|awk '{print $3}'|sed 's/\[//g'|sed 's/\]//g')"

Upvotes: 0

Related Questions