1

I need to find this number: The '3' on the second column where there is a '3' in the first column.

(This is an example. I also could need to find the '25' on the second column where there is a '36' on the first column).

The numbers on the first column are unique. There is no other row starting with a '3' on the first column.

This data is in a text file, and I'd like to use bash (awk, sed, grep, etc.)

I need to find a number on the second column, knowing the (unique) number of the first column.

In this case, I need to grep the 3 below the 0, on the second column (and, in this case, third row):

108 330
132 0
3   3
26  350
36  25
43  20
93  10
101 3
102 3
103 1

This is not good enough, because the grep should apply only to the first column elements, so the output would by a single number:

cat foo.txt | grep -w '3' | awk '{print $2}'

Although it is a text file, let's imagine it is a MySQL table. The needed query would be:

SELECT column2 WHERE column1='3'

In this case (text file), I know the input value of the first column (eg, 132, or 93, or 3), and I need to find the value of the same row, in the second column (eg, 0, 10, 3, respectively).

Regards,

Uxio
  • 33
  • 4
  • 2
    It is not clear, please do add more clear details along with clear sample of expected output. Also do add your attempts which you have put in order to solve this problem in your post too. – RavinderSingh13 Feb 28 '19 at 10:34
  • @Uxio : Do you mean something like `grep -n '^36 25$'`? – user1934428 Feb 28 '19 at 10:59
  • If my input is 36, my output should be 25. If my input is 108, my output should be 330. If my input is 101, my output should be 3. If my input is 3, my output should be 3. – Uxio Mar 01 '19 at 08:35

2 Answers2

3

Assuming you mean "find rows where the first column contains a specific string exactly, and the second contains that string somewhere within";

awk -v val="3" '$1 == val && $2 ~ $1 { print $2 }' foo.txt

Notice also how this avoids a useless use of cat.

tripleee
  • 175,061
  • 34
  • 275
  • 318
0

You can find repeated patterns by grouping the first match and looking for a repeat. This works for your example:

grep -wE '([^ ]+) +\1' infile

Output:

3   3
Thor
  • 45,082
  • 11
  • 119
  • 130
  • this will match partial columns as well, for example `93 310` and `3 32` ... however, OP's question isn't that clear too, so this might as well be the solution OP is looking for – Sundeep Feb 28 '19 at 11:33
  • 1
    @Sundeep: Indeed. I have added the only-match-at-word-boundaries (`-w`) switch which should solve that issue – Thor Feb 28 '19 at 13:14