2017-05-31 115 views
-2

您好我這裏有一個列表:設置文本格式輸出在UNIX

list_1.txt

Alpha 

Bravo 

Charlie 

和文件與以下文件名和內容的目錄:

Alpha_123。日誌

This is a sample line in the file 
error_log "This is error1 in file" 
This is another sample line in the file 
This is another sample line in the file 
This is another sample line in the file 
error_log "This is error2 in file" 
This is another sample line in the file 
This is another sample line in the file 
error_log "This is error3 in file" 
This is another sample line in the file 
This is another sample line in the file 

Alpha_123.sh

This is a sample line in the file 
This is another sample line in the file 
This is another sample line in the file 
error_log "This is errorA in file" 
This is another sample line in the file 
This is another sample line in the file 
This is another sample line in the file 
This is another sample line in the file 
error_log "This is errorB in file" 
This is another sample line in the file 
This is another sample line in the file 
error_log "This is errorC in file" 
This is another sample line in the file 

Bravo.log

Charlie.log

的Bravo.log和Charlie.log是類似內容Alpha.log

我想有這樣的輸出:

Alpha|"This is error1 in file" 

Alpha|"This is error2 in file" 

Alpha|"This is error3 in file" 

Alpha|"This is errorA in file" 

Alpha|"This is errorB in file" 

Alpha|"This is errorC in file" 

任何輸入是極大的讚賞。謝謝!

所以基本上,我想首先找到名稱中包含list_1.txt中的字符串模式的文件,然後找到錯誤消息並用|

+1

你可以用格式化的問題開始 - https://stackoverflow.com/editing-help並添加你試過要解決這個問題是什麼.. – Sundeep

+0

你的問題還不清楚。更新你的描述 – RomanPerekhrest

+0

你在做什麼 – Chris

回答

0

如果我理解正確的話,這應該這樣做:

awk -vOFS=\| 'FNR==1{file=FILENAME;sub("[.]log$","",file)}{sub("^error_log ","");print file,$0}' *.log 

解釋:

  • -vOFS=\|設置輸出域|。 (該\需要逃脫從殼|(將其當作管),你可以使用-vOFS='|'代替。)
  • FNR==1{ ... }確保該代碼是每個輸入文件只運行一次:FNR的記錄數(即行)由awk讀取到目前爲止距離當前文件。所以在處理每個文件的第一行時,這僅等於1
  • file=FILENAME只是將當前處理的輸入文件的文件名存儲在變量中供以後編輯。
  • sub("[.]log$","",file)從最終刪除.log(在[ ... ]難逃被解釋爲在正則表達式中的任意字符點(.)。你可以使用\\.代替。)(這是什麼$代表)的文件名。
  • { ...}運行每個輸入文件的每個記錄 /行的代碼。
  • sub("^error_log ","")刪除"error_log "(注意結尾的空間!),從一開始(這是什麼^代表)每行的(「記錄」)輸入。
  • print file,$0打印每個記錄(即行)的其餘部分,前面加上相應的文件名。請注意,逗號(,)將替換爲前面指定的輸出字段分隔符。您可以使用print file "|" $0而不指定OFS
  • *.log將使當前目錄中每個以.log結尾的文件成爲awk命令的輸入文件。您可以明確指定Alpha.log Bravo.log Charly.log

下面是一個使用你的list.txt構建文件名替代:

awk -vOFS=\| '{file=$0;logfile=file ".log";while(getline < logfile){sub("^error_log ","");print file,$0}}' list.txt 

解釋

  • file=$0保存當前行(REC ord)from list.txt in a variable。
  • logfile=file ".log"附加.log來獲取相應的日誌文件名。
  • while(getline < logfile){ ... }將在當前日誌文件中運行每行代碼/ 記錄

其餘的應該從上面的例子中清楚。

0

awk來救援!

awk '{gsub(/^error_log /,FILENAME"|")}1' $(awk '{print $0".log"}' list_1.txt) 

UPDATE

基礎上更新的信息,我想這就是你要找的內容。

awk '/^error_log/ {split(FILENAME,f,"_"); 
        gsub(/^error_log /,f[1]"|")}' $(awk '{print $0"_*"}' list_1.txt) 
+0

嗨@karaka,謝謝你的輸入。不幸的是,這並沒有考慮到使用list_1.txt中的字符串查找日誌文件 – peon

+0

你試過了嗎?它做你的問題。 – karakfa

+0

嗨卡拉卡,對不起,我錯過了一些細節,我的問題,請看到更新的問題。 – peon