# Using grep to get lines from a file (.tsv) that contain specific samples listed in a sample file (.tsv)

So I have a file, let's call it pcawg.tsv. It's formatted like the one down below.

Tumor sample ID  Normal sample ID  Mechanism
a                1                 deletion
b                2                 ecDNA
c                3                 ecDNA


I have a file of tumor sample ID's with the ecDNA mechanism called ecDNA_samples.tsv. It's formatted like this:

Tumor sample ID
a
b


To filter and extract the lines of pcawg.tsv that contain the tumor sample ID's in ecDNA_samples.tsv into a new file, I used this line of code below.

grep -f ecDNA_samples.tsv pcawg.tsv > ecDNA.vcf.tsv


Would this be the right code to use?

• This has been asked on unix.stackexchange.com/questions/110645/… Aug 9, 2021 at 6:46
• Is there a particular reason why you want to use grep to do this? It would be possible to make a more robust solution using R.
– gringer
Aug 9, 2021 at 23:50
• I kind of have to use this with Linux because I'm working with a Linux-based secure computing portal, since we have patient data which is confidential. Aug 10, 2021 at 0:16

This may help:

cat ecDNA_samples.tsv | xargs -I % grep '^%\s' pcawg.tsv


The command above executes grep '^<line>\s' pcawg.tsv, for each line of ecDNA_samples.tsv. Which matches the lines taken from ecDNA_samples.tsv to the sequences of characters between line start and a white-space in pcawg.tsv.

• So I ran this code as cat ecDNA_samples.tsv | xargs -I % grep '^%\s' pcawg.tsv>ecDNA_normal.tsv, but when I opened the file ecDNA_normal.tsv in my directory, the file was empty. Aug 10, 2021 at 1:55
• Use >> instead of > so an empty result at the end doesn't end up as the result instead of everything you've captured. Aug 10, 2021 at 16:19
• I see! Thank you! Aug 11, 2021 at 3:17
• @RamRS It worked. Aug 13, 2021 at 1:40

Just in case an R solution is acceptable as well, this should be fairly robust code because it properly parses the TSV files and matches up column names:

#!/usr/bin/env Rscript

library(tidyverse)