2016-08-19 48 views
0

我有一个文件,其中包含近900行Excel文件,我保存为一个制表符分隔的.txt文件。我想按照第一列中给出的数字对文本文件进行排序(它们的范围介于0和2250之间)。其他列是数字和不同长度的字母,例如。按数字排序的第一行

的myfile.txt:

0251 abcd 1234,24 bcde 
2240 efgh 2345,98 ikgpppm 
0001 lkjsi 879,09 ikol 

我已经试过

sort -k1 -n myfile.txt > myfile_num.txt 

,但我只是得到了新的名称相同的文件。我想获得:

myfile_num.txt

0001 lkjsi 879,09 ikol 
0251 abcd 1234,24 bcde 
2240 efgh 2345,98 ikgpppm 

我在做什么错?我猜这很简单,但我会很感激我能得到的任何帮助!我只知道一点点的bash脚本,所以它将会是好的,如果脚本是一个非常简单的一行,我能理解:)

谢谢:)

+1

我跑了它在我的机器,它的工作,因为它应该。你可以尝试:'sort -k1 -h myfile.txt> myfile_num.txt'? –

+0

你可以尝试'sort -k1 -t \ t'吗?在这里粘贴制表符分隔文件的问题是制表符转换为空格。应该工作,但是,因为这里数字=字符串,因为零。 –

+0

尝试'排序'没有任何选项。 – karakfa

回答

1

使用此旧的Mac OS回车转换到新行:

tr '\r' '\n' < myfile.txt | sort 
+0

你能帮助我吗?在下面的文档Proteins.txt我想要做同样的事情,但它不起作用。它只给我第一个200行输出和终端写入“tr:非法字节序列”... https://www.dropbox.com/s/umzx64c5ix90l3y/Proteins.txt?dl=0 – Ditte

+0

我环顾四周,看到tr命令可能会更好地工作。csv但它没有做任何不同的事情,当我使用你对我的新链接文件的建议命令时,仍然给我“tr:非法byt序列”...在我的大文件上使用命令的任何其他建议? – Ditte

+0

我建议用这个非ISO扩展ASCII文件开始一个新问题。 – Cyrus

0

如前所述here你可以有这个问题(以及其它伪跟进,复制question你问,是的,你没有)

tr '\r' '\n' < myfile.txt | sort -n 

它工作正常,在这里MSYS但在一些平台上,你可能需要添加:

export LC_CTYPE=C 

tr将考虑该文件为文本文件,并可能会损坏已达到最大行数限制后对其进行标记。

显然我无法测试它,但我相信它会解决问题,因为我在链接的答案上读到了什么。

+0

所以我使用命令:tr'\ r''\ n' myfile_num.txt来保存它? – Ditte

+0

如果我使用“LC_CTYPE = C tr'\ r''\ n' Myfile_num.txt”我只得到一行输出数据... – Ditte

0

python方法(兼容python 2 &),不受所有shell问题影响。非常棒,便携。我注意到输入文件有一些'0x8C'字符(奇怪的点),可能会混淆tr命令。 即正确处理如下:

import csv,sys 

# read the file as binary, as it is not really text 
with open("Proteins.txt","rb") as f: 
    data = bytearray(f.read()) 
    # replace 0x8c char by classical dots 
    for i,c in enumerate(data): 
     if c>0x7F: # non-ascii: replace by dot 
      data[i] = ord(".") 

    # convert to list of ASCII strings (split using the old MAC separator) 
    lines = "".join(map(chr,data)).split("\r") 

    # treat our lines as input for CSV reader 
    cr = csv.reader(lines,delimiter='\t',quotechar='"') 

    # read all the lines in a list  
    rows = list(cr) 
    # perform the sort (tricky) 
    # on first row, numerical, removing the leading 0 which is illegal 
    # in python 3, and if not numerical, put it at the top 

    rows = sorted(rows,key=lambda x : x[0].isdigit() and int(x[0].strip("0"))) 

# write back the file as a nice, legal, ASCII tsv file 

if sys.version_info < (3,): 
    f = open("Proteins_sorted_2.txt","wb") 
else: 
    f = open("Proteins_sorted_2.txt","w",newline='') 

cw = csv.writer(f,delimiter='\t',quotechar='"') 
cw.writerows(rows) 
f.close() 
+0

ahh ...我只有python 2.7我的osx :( – Ditte

+0

现在适用于这两个版本。 –