2016-04-26 33 views
0

我有一個每日腳本,需要在上傳到數據庫之前提取錯誤日誌並從主csv文件中刪除用戶。 我可以使用awk來提取第一列,並獲得很好的結果。但是,我從第三方應用程序返回的錯誤在錯誤列中包含一個逗號。這阻止了精確匹配並導致問題。使用嵌入到csv列中的逗號匹配模式

這是錯誤文件的樣本,我回去

"USER_ID","FIRSTNAME","LASTNAME","ERROR" 
"CA781558","Dani","Roper","parent is inactive, cannot update record" 
"BT055163","Alexis","Richardo","parent is inactive, cannot update record" 
"LN764767","Peter","Rajosz","no parent record, update denied" 
"SG839717","Jerry","Alindos","parent is inactive, cannot update record" 

我需要精確匹配爲「父母是無效的,無法更新記錄」,以此來更新父記錄,所以它可以更新。 同樣,我需要匹配「沒有父記錄」,所以我可以爲此記錄和進程添加父項。 實際上,我有一些類似的錯誤消息,需要不同的操作。用逗號匹配確切的字符串至關重要。

的預期結果是:

"USER_ID" 
"CA781558" 
"BT055163" 
"SG839717" 
+1

使用的語言,具有正確的CSV解析器。 – chepner

回答

1

使用awk你可以這樣做:

s='parent is inactive, cannot update record' 
awk -v s="\"$s\"" -F, 'NR==1 || $0 ~ s{print $1}' file 

"USER_ID" 
"CA781558" 
"BT055163" 
"SG839717" 
0

我會用一個適當的CSV解析器去。以下是使用核心模塊Text::ParseWords的示例,因此您無需從CPAN下載它。

perl -MText::ParseWords -lne ' 
    @line = parse_line(",", 1, $_); 
    print $line[0] if $.==1; 
    print $line[0] if $line[3] =~ /parent is inactive, cannot update record/; 
' file 
"USER_ID" 
"CA781558" 
"BT055163" 
"SG839717" 
1

只需使用這個(awk是矯枉過正爲了這個目的):

cat infile.txt | grep 'parent is inactive, cannot update record' | cut -d ',' -f1