2015-11-18 46 views
0

我有兩個文件提取file1.txt行並使用shell合併到file2.txt?

FILE1.TXT(由用戶註冊生成的)

1 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 
2 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 
3 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 
4 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 

FILE2.TXT(由用戶作業提交產生,並具有僅1行)

CellPhone MLSNUMBER PRICE ANDANOTHER20FIELDS 

蜂窩電話號碼總是在相同的格式3215551234在這兩個文件

我想搜索cell1.txt的手機號碼,並添加完成特定的行到file2.txt的開頭

我已經用awk和sed在最後一天左右得到了這些,但是這讓我難住了。我相信awk和join是方式,但這是我的技能水平之外的方式。

+0

不'加入FILE1.TXT FILE2.TXT -1 4 -2 1'產生你想要什麼? – Azad

回答

0

join更改您的字段並需要排序的文件。這聽起來像你正在尋找更像這樣的東西:

grep " $(awk '{print $1}' file2.txt) " file1.txt|cat - file2.txt 

假設file1.txt中的手機號碼周圍有空格。

0

如果你要搜索file1.txt的手機號碼在file2.txt

$ awk ' 
    # Only runs on the first file (file2.txt) 
    NR==FNR { 
    # Register each phone number in an array 
    cp[$1]=1 
    # Skip the next part of the execution 
    next 
    } 
    # Only running for file1.txt 
    # Check to see if the phone number in file1.txt is in the array 
    $4 in cp # This is a short way of writing: $4 in cp {print $0}; 
' file2.txt file1.txt 
1 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 
2 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 
3 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 
4 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 

如果你想在年底來連接file2.txt可以簡單的寫| cat - file2.txt

awk 'NR==FNR{cp[$1]=1;next}$4 in cp' file2.txt file1.txt | cat - file2.txt 

如果你有多次電話編號爲file2.txt並且希望輸出爲:

1 Name1 Name2 Phone1 Email ... 
2 Name1 Name2 Phone1 Email ... 
Phone1 MLSNUMBER PRICE ANDANOTHER20FIELDS 
3 Name1 Name2 Phone2 Email ... 
4 Name1 Name2 Phone2 Email ... 
Phone2 MLSNUMBER PRICE ANDANOTHER20FIELDS 

你可以使用這個如果 - 假設file1.txt被預分類上的電話號碼:

$ awk ' 
    # Only runs on the first file (file2.txt) 
    NR==FNR { 
    # Register each phone number in an array 
    cp[$1]=$0 
    # Skip the next part of the execution 
    next 
    } 
    # Print current line same as 1==1{print $0} 
    1; 
    FNR>1 && prev!=$4 { 
    print prevLine 
    } 
    { 
    prev=$4 
    prevLine=cp[$4] 
    } 
    END { 
    print prevLine 
    } 
' file2.txt file1.txt 
1 Name1 Name2 Phone1 Email ... 
2 Name1 Name2 Phone1 Email ... 
1 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 
Phone1 MLSNUMBER PRICE ANDANOTHER20FIELDS 
2 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 
3 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 
4 Name1 Name2 CellPhone Email ANDANOTHER20FIELDS 
CellPhone MLSNUMBER PRICE ANDANOTHER20FIELDS 
相關問題