2014-11-24 73 views
0

我必須用一堆數據txt文件(在一種情況下,每行上有一個字符串,在其他文件中末尾有換行符結束只是簡單的字符串,用空格但沒有明確的方式來分解數據)。但文件組由超鏈接組成。這些數據當前不存在於表格中 - 我不確定將其導入適當的列/數據字段的最佳方式)。如何在兩個txt文件中找到一個匹配的字符串

我需要做的就是拉出兩個文件中出現的數據「字符串」。

例子文件1:

http://-28uw.c.cr http://www.2xik.com http://www.365cnblog.cn http://www.blogactif.net  http://www.blogactifs.com http://www.blogalbums.com http://www.blogallerys.com ... etc. 

示例文件2:

http://en.wikipedia.org 
http://stayyoungafter50.com 
http://108.160.146.227 
http://10tv.com 
http://110mb.com 

我不關心WWW,HTTP或HTTPS所有我想要做的就是找到這兩個文件中匹配10tv.com 。或cnn.com,就是這樣。

有什麼建議嗎?

+0

你的問題很模糊,所以很難給出任何價值的答案。 我建議的是用你選擇的語言編寫一個小程序,讀取2個文件。 當它處理第一個文件時 - 將這些單詞添加到字典對象或等價物。希望你可以使用像任何空白邏輯將被視爲分隔符(新行,空格,製表符)。當你存儲它時,你會修剪你不關心的東西,比如http://和https://等等。 然後你讀第二個文件 - 檢查(修剪的)單詞是否在字典中。如果它們是,將它們插入到數據庫中。 – bkr 2014-11-24 19:38:46

+0

作爲附加說明 - 我不相信-28uw.c.cr是一個有效的主機名。主機名標籤不應以連字符開頭或結尾 - http://en.wikipedia.org/wiki/Hostname。 – bkr 2014-11-24 19:45:31

+0

@bkr感謝您的建議,我不負責這些主機名的有效性是我提供的文件。最終我使用sql /數據庫,所以我想用sql的soe形式來比較數據。但我不確定什麼是最好的。 – YelizavetaYR 2014-11-24 19:50:55

回答

0

以下是我想接近它(但使用PowerShell的,而不是SQL):

clear 
pushd c:\myPath\myFolder\ 

#read in the contents of the files 
$file1 = get-content("file1.txt") 
$file2 = get-content("file2.txt") 

#loop through each row of the whitespace separated file 
$file1 = $file1 | %{ 
    #for each line, split on whitespace characters, returning the results back in a single column 
    $_ -split "\s" | %{$_} 
} 
#compare the two files for matching data & output this info 
compare-object $file1 $file2 -IncludeEqual -ExcludeDifferent | ft -AutoSize 

popd 

注:忽略協議,只需從使用類似的技術我們對空間的分割字符串中刪除;即正則表達式,這次用替換而不是拆分。

clear 
pushd c:\temp 

$file1 = get-content("file1.txt") 
$file2 = get-content("file2.txt") 

$file1 = $file1 | %{ 
    $_ -split "\s" | %{ 
     $_ -replace ".*://(.*)",'$1' 
    } 
} 

$file2 = $file2 | %{ 
    $_ -replace ".*://(.*)",'$1' 
} 

compare-object $file1 $file2 -IncludeEqual -ExcludeDifferent | ft -AutoSize 

然而,你應該更喜歡SQL解決方案,試試這個(MS SQL服務器):

create table f1(url nvarchar(1024)) 
create table f2(url nvarchar(1024)) 

BULK INSERT f1 
FROM 'C:\myPath\myFolder\file1.txt' 
WITH (ROWTERMINATOR =' ', FIRSTROW = 1) 

BULK INSERT f2 
FROM 'C:\myPath\myFolder\file2.txt' 
WITH (FIRSTROW = 1) 
go 

delete from f1 where coalesce(rtrim(url),'') = '' 
delete from f2 where coalesce(rtrim(url),'') = '' 

select x.url, x.x, y.y 
from 
(
    select SUBSTRING(url,patindex('%://%',url)+3, len(url)) x 
    , url 
    from f1 
) x 
inner join 
(
    select SUBSTRING(url,patindex('%://%',url)+3, len(url)) y 
    , url 
    from f2 
) y 
on y.y = x.x 
+1

這看起來不錯。我會玩這個。謝謝。 – YelizavetaYR 2014-11-24 21:08:28

相關問題