我有一个看起来像这样的文件
chrom_pos chrom position BF window_id
"Chr01__69500112" 1 69500112 10.1214802 "window_1391"
"Chr01__69500129" 1 69500129 -7.59047205 "window_1391"
"Chr01__69500156" 1 69500156 8.475337 "window_1391"
"Chr01__69500197" 1 69500197 10.37964237 "window_1391"
"Chr01__69500233" 1 69500233 -8.59724917 "window_1391"
...
...
...
"Chr01__87300054" 1 87300054 -2.1058919 "window_1747"
"Chr01__87300107" 1 87300107 2.39553299 "window_1747"
"Chr01__87300686" 1 87300686 -11.03002514 "window_1747"
"Chr01__87300694" 1 87300694 -5.9689038 "window_1747"
"Chr01__87300709" 1 87300709 -5.52387942 "window_1747"
"Chr01__87300800" 1 87300800 -3.63119004 "window_1747"
...
...
...
"Chr17__200219189" 17 200219189 -2.30332074 "window_59705"
"Chr17__200219216" 17 200219216 15.04053029 "window_59705"
"Chr17__200219284" 17 200219284 -3.74266312 "window_59705"
"Chr17__200220333" 17 200220333 -1.91153668 "window_59705"
"Chr17__200241059" 17 200241059 -11.47407263 "window_59705"
对于列中的每个窗口窗口ID,我想知道起始位置(位置认为窗口ID从它开始)和结束位置(位置认为窗口ID最终得到它),并得到如下输出:
window_id chrom starting_positon ending_position
window_1391 1 69500112 69500233
window_1747 1 87300054 87300800
window_59705 17 200219189 200241059
每个窗口的条目都是有序的,并且也是正链的。
答案1
使用awk
:
NR == 1 { next } # skip header
$5 != window { # new (or first) window
if (window != "") # unless this is the first window, print the collected data
print window, chrom, start, end
# collect data for next window
chrom = $2
start = $3
window = $5
}
{ end = $3 } # always update the end position
# at the end, print the collected data for the last window
END { print window, chrom, start, end }
运行这个:
$ awk -f script.awk file
"window_1391" 1 69500112 69500233
"window_1747" 1 87300054 87300800
"window_59705" 17 200219189 200241059
使用制表符作为输出分隔符:
$ awk -v OFS='\t' -f script.awk file
"window_1391" 1 69500112 69500233
"window_1747" 1 87300054 87300800
"window_59705" 17 200219189 200241059
稍微更花哨的版本,将用于输出的代码收集到函数中。该函数还输出一个标头并从原始窗口 ID 中去掉双引号。
function output() {
if (window == "")
# no previous window, output header
print "window_id", "chrom", "starting_posititon", "ending_position"
else {
# strip the first and last characters from window ID (the quotes)
# then output
w = substr(window, 2, length(window) - 2)
print w, chrom, start, end
}
}
NR == 1 { next } # skip header
$5 != window { # new (or first) window
output()
# collect data for next window
chrom = $2
start = $3
window = $5
}
{ end = $3 } # always update the end position
# at the end, print the collected data for the last window
END { output() }
运行它:
$ awk -v OFS='\t' -f script.awk file
window_id chrom starting_posititon ending_position
window_1391 1 69500112 69500233
window_1747 1 87300054 87300800
window_59705 17 200219189 200241059