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?

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?).

  • Thank you but It is not working. – Eric González Aug 7 '18 at 16:13
  • Define 'not working'? It works for me given your extremely limited sample data in the post. – DopeGhoti Aug 7 '18 at 18:04
  • It is working, sorry I did something wrong. – Eric González Aug 7 '18 at 21:55
  • No worries; glad to have helped. – DopeGhoti Aug 8 '18 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.