我有:
$ cat file1.csv (tab delimited)
R923E06 273911 2990492 2970203 F Resistant
R923F06 273910 2990492 2970203 F Resistant
R923H02 273894 2970600 2990171 M Resistant
和:
$ cat file2.txt (space delimited and it's a large file)
R923E06 CC GG TT AA ...
R923F06 GG TT AA CC ...
R923H02 TT GG CC AA ...
如何将file2.txt
中的第一列替换为file1.csv
中的6列?
答案 0 :(得分:2)
使用join
,您可以这样做:
join <(sed -e 's/\t/ /g' file1.csv) <(cat file2.txt)
sed
将制表符更改为空格
join
到公共字段中两个文件的连接行。
输出:
R923E06 273911 2990492 2970203 F Resistant CC GG TT AA ...
R923F06 273910 2990492 2970203 F Resistant GG TT AA CC ...
R923H02 273894 2970600 2990171 M Resistant TT GG CC AA ...
答案 1 :(得分:0)
看看这个AWK示例:
awk 'FNR == NR { d[$1] = $0; next } { $1 = d[$1] } 1' file1.csv file2.txt
在这里,我将file2.txt
中的第一列替换为file1.csv
的相应行(6列)。
输出:
R923E06 273911 2990492 2970203 F Resistant CC GG TT AA ...
R923F06 273910 2990492 2970203 F Resistant GG TT AA CC ...
R923H02 273894 2970600 2990171 M Resistant TT GG CC AA ...
如果要在结果中用制表符分隔所有内容,则可以添加gsub(/[[:space:]]/,"\t")
以用制表符替换任何空格或制表符:
awk 'FNR == NR { d[$1] = $0; next } { $1 = d[$1]; gsub(/[[:space:]]/,"\t") } 1' file1.csv file2.txt
答案 2 :(得分:0)
#import pandas
import pandas as pd
#read file1.csv
#set index_col as false if file has delimiters at the end
file1 = pd.read_csv( 'file1.csv', ' ', index_col = False, names =
['1','2','3','4','5','6']);
#read file2.txt, read_csv can read txt files as well
#set index_col as false if file has delimiters at the end
file2 = pd.read_csv( 'file2.csv', ' ', index_col = False, names =
['1','2','3','4','5']);
#drop first column
file2.drop( '1', axis = 1, inplace = True )
#concat both frames
final = pd.concat([file1, file2], axis = 1)
#you might end up with mixed column names you can change it by using
final.columns = ['col1', 'col2', ....]
#save as csv
final.to_csv('out.csv',sep='\t')