我有一个看起来很混乱的文件:
contig_1 bin.0013 Rhizobium flavum (taxid 1335061)
contig_2 Alphaproteobacteria (taxid 28211)
contig_3 bin.009
contig_4 bin.008 unclassified (taxid 0)
contig_5 bin.001 Fluviicoccus keumensis (taxid 1435465)
contig_12 bin.003
我希望它以制表符分隔的列和为零的空白位置正确显示:
contig_1 bin.0013 Rhizobium flavum (taxid 1335061)
contig_2 0 Alphaproteobacteria (taxid 28211)
contig_3 bin.009 0
contig_4 bin.008 unclassified (taxid 0)
contig_5 bin.001 Fluviicoccus keumensis (taxid 1435465)
contig_12 bin.003 0
如果我使用像sed 's/ /,/g' filename
这样的逗号,则除了1-2和2-3列之外,还插入逗号。
如果选择awk
,请尝试以下操作:
awk -v OFS="\t" '
NR==FNR {
# in the 1st pass, detect the starting positions of the 2nd field and the 3rd
sub(" +$", "") # it avoids misdetection due to extra trailing blanks
if (match($0, "[^[:blank:]]+[[:blank:]]+")) {
# RLENGTH holds the ending position of the 1st blank
if (col2 == 0 || RLENGTH < col2) col2 = RLENGTH + 1
if (match($0, "[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+")) {
# RLENGTH holds the ending position of the 2nd blank
if (col3 == 0 || RLENGTH < col3) col3 = RLENGTH + 1
}
}
next
}
{
# in the 2nd pass, extract the substrings in the fixed position and reformat them
# by removing extra spaces and putting "0" if the fiels is empty
c1 = substr($0, 1, col2 - 1); sub(" +$", "", c1); if (c1 == "") c1 = "0"
c2 = substr($0, col2, col3 - col2); sub(" +$", "", c2); if (c2 == "") c2 = "0"
c3 = substr($0, col3); gsub(" +", " ", c3); if (c3 == "") c3 = "0"
# print c1, c2, c3 # use this for the tab-separated output
printf("%-12s%-12s%-s\n", c1, c2, c3)
}' file file
输出:
contig_1 bin.0013 Rhizobium flavum (taxid 1335061)
contig_2 0 Alphaproteobacteria (taxid 28211)
contig_3 bin.009 0
contig_4 bin.008 unclassified (taxid 0)
contig_5 bin.001 Fluviicoccus keumensis (taxid 1435465)
contig_12 bin.003 0
printf
以在视觉上对齐输出。您可以切换到tab separated values
根据偏好。