2017-01-13 35 views
0

我有两个.dat文件。首先是文本ID:名称和第二个ID:大小。我必须创建第三个文件,它将是ID:name:size。 我在终端非常新的,我做了这样的事情:如何使用sed的grep结果

#!/bin/bash 
egrep '[[:alnum:]]+:' file2.dat | sort > new.dat 
cat new.dat > file2.dat 
egrep '[[:alnum:]]+:' file1.dat | sort > new.dat 
cat new.dat > file1.dat 

while read -r line 
do 
    echo "$line" > temp 
    egrep -o ':[[:alnum:]]+' temp 
done < file2.dat 

接下来的想法是使用SED的/ $ //'new.dat用文字写出来egrep的结合,可我就是不明白。

我的问题是,如果有可能我怎么能用其他方式做,或者我怎么能结合这个命令。

+1

请加样品输入所需输出为输入样本您题。 – Cyrus

+0

输入格式在文本中描述(ID:名称,ID:大小) – setempler

回答

2

你可以看看man join,而不是在bash和grep中使用循环。

例如

file1.dat:

a:foo 
b:bar 
c:baz 

File2.DAT的:

a:1 
b:2 

运行:

join -t : file1.dat file2.dat

或詹姆斯·布朗暗示(对于未排序文件):

join -t : <(sort file1.dat) <(sort file2.dat)

获得:

a:foo:1 
b:bar:2 
+0

谢谢,这工作:) – Princo

+0

伟大的欢迎!如果需要添加不匹配的行,请查看“-a”参数... – setempler

+2

请记住,使用'join'时需要对文件进行排序。如果没有,你可以'加入-t:<(sort file1.dat)<(sort file2.dat)'。 –

1

这里有一个在AWK:

$ awk -F':' '$1 in a{print a[$1] FS $2;next}{a[$1]=$0}' f1 f2 
a:foo:1 
b:bar:2 

解释:

awk -F':' '    # use : as field separator 
$1 in a {    # if key in the first field has already been seen 
    print a[$1] FS $2; # output corresponding array (=record from f1) and $2 of f2 
    next }    # no need to process this record further, skip to next 
{ 
    a[$1]=$0   # store record from f1 to hash a using first field as a key 
}' f1 f2