2016-04-18 25 views
2

此解決方案將成爲腳本的一部分。在bash中從行中提取兩個子字符串,然後連接它們

給定一個錯誤日誌,我需要提取失敗的狀態/失敗原因和用戶名,然後連接它們以便輸出可以通過電子郵件發送。

我的輸出應該是這個樣子:

Operation status: failed,Job Description not updated because this is not a matching Job Description ID.,username=FOO 
Operation status: failed,Job Description not updated because this is not a matching Job Description ID.,username=BAR 

在錯誤日誌文件中的每一行非常類似於此:

"{ Operation status: failed,Job Description not updated because this is not a matching Job Description ID.,Sent Data:{lastAppraisalScore=0.0, country=null, jobTitle=LABORER..., username=FOO},...sendAcctActNotif=N}}" 

有文件中沒有省略號;每一行所包含的內容都比所示的多得多,但我只顯示了重要的部分。

+1

你能分享一下你的研究工作嗎?你是否嘗試用'set -x'選項來調試腳本? – Inian

+3

每行是否有效JSON?如果是這樣,你可以通過將每行傳遞給'jq'並選擇'Operation status'和'username'鍵來實現。 –

+0

我還沒有嘗試用'set -x'選項進行調試。 'egrep -o「操作狀態:」輸入「部分地返回我需要的內容,但需要提取直到第一個」。「,這樣我才能拾取整個錯誤代碼。 – sharpmartin6

回答

1

使用this answer您可以提取部分行(如果它總是以相同的方式)。然後,您可以通過在線處理您的文件行:

while read line; do 
    status=`grep -oP '(?<=Operation status:).*?(?=Sent)' <<< "$line"` 
    user=`grep -oP '(?<=username=).*?(?=})' <<< "$line" | head -n 1` 
    echo "Operation status:" $status "username="$user 
done < file.txt 

我的例子file.txt的:

{ Operation status: failed1,Job Description not updated because this is not a matching Job Description ID.,Sent Data:{lastAppraisalScore=0.0, country=null, jobTitle=LABORER..., username=FOO1}, {username=BAR1}...sendAcctActNotif=N}} 
{ Operation status: failed2,Job Description not updated because this is not a matching Job Description ID.,Sent Data:{lastAppraisalScore=0.0, country=null, jobTitle=LABORER..., username=FOO2}, {username=BAR2}...sendAcctActNotif=N}} 
{ Operation status: failed3,Job Description not updated because this is not a matching Job Description ID.,Sent Data:{lastAppraisalScore=0.0, country=null, jobTitle=LABORER..., username=FOO3}, {username=BAR3}...sendAcctActNotif=N}} 

我的輸出:

Operation status: failed1,Job Description not updated because this is not a matching Job Description ID., username=FOO1 
Operation status: failed2,Job Description not updated because this is not a matching Job Description ID., username=FOO2 
Operation status: failed3,Job Description not updated because this is not a matching Job Description ID., username=FOO3 
+0

這工作,謝謝你。但是,我只是意識到錯誤日誌的每一行都有兩個'username ='實例,所以兩者都被返回!我如何才能返回每行中用戶名的第一個實例? – sharpmartin6

+1

@ sharpmartin6您可以使用|頭-n 1保留第一個元素(第一行)。看看我的編輯 – Fabich

+0

感謝您的快速回復。 '| head -n 1'只返回文件中的第一個元素。是否有可能只用'grep'在每行中返回第一個用戶名實例? – sharpmartin6

2

一個簡單的sed替換似乎更加充足。

sed -n '/^"{ Operation status: failed,/!b 
    s///;s/,Sent.*, username=/\t/;s/}.*//p' file 

這將搜索第一個表達式;如果找不到,我們繞過這條線。否則,我們將沒有匹配的字符串替換掉,然後繼續替換我們不想保留的其他字符串,最後打印剩下的字符串。

+0

當我嘗試運行代碼時,出現此錯誤:'sed:無法找到跳轉到/// /'的標籤。 – sharpmartin6

+0

嘗試在'b'後添加分號。我希望所有的'sed'方言在這裏都有一個換行符,作爲語句分隔符,但顯然不是。 – tripleee

+0

但是,我添加了一個缺少'!'(不) – tripleee

相關問題