1

I have the following file:

chr1    157784  157887  U6  0   -
chr1    564813  564881  miRNA   0   +
chr1    564879  564950  tRNA    0   -
chr1    564952  565019  tRNA    0   +
chr1    566062  566129  piRNA   0   +
chr1    566137  566205  tRNA    0   -

If the expression word in the 4th column does NOT start with "piRNA" OR "miRNA", then replace with the word "rfam"

expected output:

chr1    157784  157887  rfam    0   -
chr1    564813  564881  miRNA   0   +
chr1    564879  564950  rfam    0   -
chr1    564952  565019  fram    0   +
chr1    566062  566129  piRNA   0   +
chr1    566137  566205  rfam    0   -

Note: There will be many different names in field 4, not just U6 and tRNA. This need to work for any word that is not piRNA or miRNA.

  • What have you tried? Please show us your attempt. – jasonwryan Feb 29 '16 at 0:30
1
awk -v OFS='\t' '$4 !~ /^[pm]iRNA/ { $4 = "rfam" } ; { $4 = $4 ; print }' file

This does exactly what you asked for - if field 4 doesn't match the regexp ^[pm]iRNA, set it to rfam. Then print the line whether it was changed or not.

Note: I've set the Output Field Separator (OFS) to a tab to ensure consistent output, and added $4 = $4 before the print statement (which has the side-effect of causing the field separator in the output line to be changed to OFS) - otherwise lines that have been changed will have the OFS as the default (a single space) while unchanged lines will be unchanged from what they were in the original file, potentially causing the columns to not line up correctly when viewed with in a terminal with cat or whatever.

  • Thank you! This works perfectly. Also thank you for the thorough explanation of the OFS print statement. I was mainly getting caught up in the regular expression of how to call both of the word piRNA and miRNA. Is there a way to do this with an or statement? I've tried using: awk -v OFS='\t' '$4 !~ /^piRNA || miRNA/ { $4 = "rfam" } ; { $4 = $4 ; print }' file – Anonymous Feb 29 '16 at 5:18
  • almost right - an "or" in regex is | (single |) not ||, so /^piRNA|^miRNA/ (note that both sub-expressions need the ^ anchor - alternatively, use ^(miRNA|piRNA). It's shorter and IMO simpler to use a character class ^[pm]iRNA as I did. – cas Feb 29 '16 at 6:58
  • Great! Thanks so much for your explanations! – Anonymous Feb 29 '16 at 7:20

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.