2012-07-19 41 views
0

我已經完成了我的研究,但無法找到我的問題的解決方案。 我想提取字符串中的所有有效單詞(以字母開頭),並用下劃線(「_」)連接它們。我尋找與AWK,sed的或grep的溶液等在他們之間打印有效的詞與_

是這樣的:

echo "The string under consideration" | (awk/grep/sed) (pattern match) 

實施例1

輸入:

1.2.3::L2 Traffic-house seen during ABCD from 2.2.4/5.2.3a to 1.2.3.X11 

希望的輸出:

L2_Traffic_house_seen_during_ABCD_from 

實施例2

輸入:

XYZ-2-VRECYY_FAIL: Verify failed - Client 0x880016, Reason: Object exi 

所需的輸出:

XYZ_VRECYY_FAIL_Verify_failed_Client_Reason_Object_exi 

實施例3

輸入:

ABCMGR-2-SERVICE_CRASHED: Service "abcmgr" (PID 7582) during UPGRADE 

所需的輸出:

ABCMGR_SERVICE_CRASHED_Service_abcmgr_PID_during_UPGRADE 
+0

歡迎堆棧溢出。請閱讀[如何問](http://stackoverflow.com/questions/how-to-ask),[你有什麼嘗試?](http://mattgemmell.com/2008/12/08/what-have - 你試過/),[如何提出問題的智能方式](http://catb.org/esr/faqs/smart-questions.html)。 – 2012-07-19 09:43:58

+0

在第一個例子中,爲什麼最後的'to'這個詞不包括在內?爲什麼包含'L2'而不是'X11'? – Birei 2012-07-19 10:09:18

回答

2

這可能會爲你工作(GNU SED):

sed 's/[[:punct:]]/ /g;s/\<[[:alpha:]]/\n&/g;s/[^\n]*\n//;s/ [^\n]*//g;y/\n/_/' file 
1

一個perl單線。它搜索任何字母字符,然後搜索字邊界中所包含的任意數量的單詞字符。使用/g標誌爲每行嘗試幾個匹配項。

內容infile

1.2.3::L2 Traffic-house seen during ABCD from 2.2.4/5.2.3a to 1.2.3.X11 
XYZ-2-VRECYY_FAIL: Verify failed - Client 0x880016, Reason: Object exi 
ABCMGR-2-SERVICE_CRASHED: Service "abcmgr" (PID 7582) during UPGRADE 

Perl命令:

perl -ne 'printf qq|%s\n|, join qq|_|, (m/\b([[:alpha:]]\w*)\b/g)' infile 

輸出:

L2_Traffic_house_seen_during_ABCD_from_to_X11 
XYZ_VRECYY_FAIL_Verify_failed_Client_Reason_Object_exi 
ABCMGR_SERVICE_CRASHED_Service_abcmgr_PID_during_UPGRADE 
1

一個使用awk,隨着script.awk內容的方法:

BEGIN { 
    FS="[^[:alnum:]_]" 
} 

{ 
    for (i=1; i<=NF; i++) { 
     if ($i !~ /^[0-9]/ && $i != "") { 
      if (i < NF) { 
       printf "%s_", $i 
      } 
      else { 
       print $i 
      } 
     } 
    } 
} 

運行,如:

awk -f script.awk file.txt 

另外,這裏是一個班輪:

awk -F "[^[:alnum:]_]" '{ for (i=1; i<=NF; i++) { if ($i !~ /^[0-9]/ && $i != "") { if (i < NF) printf "%s_", $i; else print $i; } } }' file.txt 

結果:

L2_Traffic_house_seen_during_ABCD_from_to_X11 
XYZ_VRECYY_FAIL_Verify_failed_Client_Reason_Object_exi 
ABCMGR_SERVICE_CRASHED_Service_abcmgr_PID_during_UPGRADE 
相關問題