1

I am trying to compare columns of the same file. The table looks like this:

  G  A  AA  GG CC TT CT
  C  T  CC  TT GG GG AA

What I want to do is to compare the first and second column with the rest, and see if they contain part of the first or second column.

Something like this:

awk '$1 == ^$3 || $2 == ^$3 {print $0}' File.txt

or like this

awk '$1 ~ /$3/ || $2 ~ /$3/ {print $0}' File.txt

But is not working. How can I make these kinds of comparisons between columns?

4 Answers 4

1

You have your comparisons backwards. Try these alternatives instead:

awk '$3 ~ $1 || $3 ~ $2 { print }' inputfile
awk 'match( $3, $1 ) || match( $3, $2 ) { print }' inputfile

In your sample code, you were trying $1 ~ $3 which expands to C ~ /CC/ (does the expression /CC/ match the string C?) rather than CC ~ /C/ (does the expression /C/ match the string CC?).

4
  • Thank you but It is not working. Commented Aug 7, 2018 at 16:13
  • Define 'not working'? It works for me given your extremely limited sample data in the post.
    – DopeGhoti
    Commented Aug 7, 2018 at 18:04
  • It is working, sorry I did something wrong. Commented Aug 7, 2018 at 21:55
  • No worries; glad to have helped.
    – DopeGhoti
    Commented Aug 8, 2018 at 15:36
1
$ awk '{ for (i=3; i<=NF; ++i) if (match($i,$1) || match($i,$2)) { print; next } }' file
G A AA GG CC TT CT
C T CC TT GG GG AA

Testing on a file where we the test fails for two lines and succeeds for two lines:

$ cat file
G A AA GG CC TT CT
C T AG AA GG GG AA
G C AA AA TT TT AT
C T CC TT GG GG AA

$ awk '{ for (i=3; i<=NF; ++i) if (match($i,$1) || match($i,$2)) { print; next } }' file
G A AA GG CC TT CT
C T CC TT GG GG AA

The awk script goes through all columns from column 3 onwards and compares each column with column 1 and 2. If the character in column 1 or 2 is present in any of the other columns, the line is immediately printed and the script continues with the next line.

0

Try (with data stolen from Kusalananda's sample)

awk '{PAT = "[" $1 $2 "]"} gsub (PAT, "&") > 2' file
G A AA GG CC TT CT
C T CC TT GG GG AA
0

You could try this approach:

grep -P '^(\S+) (\S+) .*(\1|\2)' gene.file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .