你能帮我合并两个文件吗? 实际上它的行应该合并,每行都有相同的ID(例如,在这个例子中为1或2)。
1#first#scott#prince01
2#second#scott#prince02
1#scott#prince01#88129
2#scott#prince02#34
1#first#scott#prince01#1#scott#prince01#88129
2#second#scott#prince02#2#scott#prince02#34
答案 0 :(得分:4)
在您的简单情况下,使用join
命令就足够了:
join -t'#' File1 File2
输出:
1#first#scott#prince01#scott#prince01#88129
2#second#scott#prince02#scott#prince02#34
-t'#'
- 指定字段分隔符答案 1 :(得分:0)
在awk中:
$ awk 'BEGIN{FS=OFS="#"}NR==FNR{a[$1]=$0;next}($1 in a){print a[$1],$0}' file1 file2
1#first#scott#prince01#1#scott#prince01#88129
2#second#scott#prince02#2#scott#prince02#34
说明:
$ awk '
BEGIN{
FS=OFS="#" # set FS AND OFS to #
}
NR==FNR { # for the first file
a[$1]=$0 # hash records, use $1 as key
next # skip to next record
}
($1 in a) { # for the second file, if key found in the hash
print a[$1],$0 # output
}' file1 file2
答案 2 :(得分:0)
更多方法(我假设文件已订购)
<强>输入强>
$ cat f1
1#first#scott#prince01
2#second#scott#prince02
$ cat f2
1#scott#prince01#88129
2#scott#prince02#34
使用 pr
$ pr -mtJS'#' f1 f2
1#first#scott#prince01#1#scott#prince01#88129
2#second#scott#prince02#2#scott#prince02#34
使用 paste
$ paste -d'#' f1 f2
1#first#scott#prince01#1#scott#prince01#88129
2#second#scott#prince02#2#scott#prince02#34
答案 3 :(得分:0)
$ awk '{a[FNR]= a[FNR]=="" ? $0 :a[FNR]"#"$0}END{for(i in a)print a[i]}' File1 File2
1#first#scott#prince01#1#scott#prince01#88129
2#second#scott#prince02#2#scott#prince02#34
简要说明,
a[FNR]= a[FNR]=="" ? $0 :a[FNR]"#"$0
:如果[FNR]中没有初始值,则将其另存为$0
,否则存储a[FNR]"#"$0
。