Extract a Column from a TSV Stream

Foundational Bash Foundations Bash awk cut Tabular Data
Significance:

Genomic annotation lives in tab-separated files — BED, GFF, VCF and count matrices are
all variations on the same theme. Pulling out a single column is how you get a gene list out of a
differential expression table or a chromosome list out of a BED file, and it is almost always the first
step before sorting, counting or joining.

Statement

Tab-separated text arrives on standard input. The first line is a header and must be
skipped.

The first line of input before the data is not the header — instead, the very first line of standard
input is a single integer k, the 1-based index of the column to extract. The second line is the header
row, and everything after that is data.

Print the value of column k from every data row, one per line, in input order.

Input — read from standard input
Variable Type Description
k
line 1
int The 1-based column index to extract
1 <= k <= 20
header
line 2
str The tab-separated header row, which is skipped
1 <= columns <= 20
rows
line 3..n
str Tab-separated data rows
0 <= rows <= 1000

These variables are already read for you in the starter code on the right.

Output

str the value of column k from each data row, one per line, in input order

Sample Cases
Sample 1
Input
2
gene	logFC	pval
TP53	2.5	0.001
BRCA1	-1.2	0.03
EGFR	0.4	0.5
Expected Output
2.5
-1.2
0.4
Column two is extracted from each data row, skipping the header.
Sample 2
Input
1
chrom	start	end
chr1	100	200
chr2	300	400
Expected Output
chr1
chr2
The first column is extracted.

Submit also runs your code against 3 hidden test cases. Hidden inputs are never shown — if one fails you'll get its number and a description of the mismatch, not the data.

Constraints
  • Fields are separated by single tab characters
  • The header row is skipped and never printed
  • k is guaranteed to be a valid column index for every row
  • If there are no data rows, print nothing
Further Reading
  • Read k first with read, then pipe the remainder of standard input to your extractor.
  • awk -v c="$k" 'NR>1 {print $c}' skips the header and prints the chosen field.
  • Set the field separator explicitly with -F'\t' so values containing spaces stay intact.

Judged against GNU Bash 5.1.0.


My Notes
Log in to save personal notes.
Console output will appear here when you click Run Code or Submit...
Expected: k (int), header (str), rows (remaining lines)
Next Problem
Filter Rows by Numeric Threshold