2017-01-13 39 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