2013-04-22 71 views
1

我正在通過一個非常複雜和長期的多條件語句來完成此任務,並且想知道是否有人知道更簡單的方法。我有一個我試圖解析的多列/多行列表。我需要做的是將第一行的「*」放在第五位,並將所有條目複製到接下來幾行的空白處,然後丟棄原來的最上一行。這有點複雜,有時接下來的幾行在所有其他字段中可能沒有空的空間(參見原始列表的下半部分)。如果是這種情況,我想要額外輸入(下面的Q1),並將它放在行的末尾,放在一個新列中。從一個列解析多個行的shell腳本

最初的名單:

A B C D ***** F G 
    E1 
    E2 
    E3 
Q R S T ***** V W 
    U1 
Q1 U2 

最終輸出:

A B C D E1 F G 
A B C D E2 F G 
A B C D E3 F G 
Q R S T U1 V W 
Q R S T U2 V W Q1 

預先感謝幫助!

+0

Awk是一個很好的方式來做到這一點,顯示你已經嘗試過,有人應該幫助你解決它。 – Barmar 2013-04-22 19:32:38

+0

@Barmar不,我絕對不希望任何人爲我寫信。如果有人能夠指引我正確的方向。現在我正在使用'for my $ myoutput | awk'{print $ 5}''逐行進行檢查,看看第五個字段是否全是*********,在這一點我開始一個新行,新的字段名稱從$ 1,2,3 ,4,6,7。 – fembot 2013-04-22 19:44:28

+2

你應該在awk中完成整個事情,就像在sudo_O的答案中一樣。 – Barmar 2013-04-22 19:46:54

回答

1

簡明/神祕的一個班輪:

awk '/[*]/{f=$0;p="[*]+";next}{r=$2?$2:$1;sub(p,r,f);p=r;print $2?f" "$1:f}' file 
A B C D E1 F G 
A B C D E2 F G 
A B C D E3 F G 
Q R S T U1 V W 
Q R S T U2 V W Q1 

說明:

/[*]+/ {     # If line matches line with pattern to replace 
    line = $0    # Store line 
    pat="[*]+"   # Store pattern 
    next     # Skip to next line 
} 
{ 
    if (NF==2)   # If the current line has 2 fields 
     replace = $2  # We want to replace with the second 
    else     # Else 
     replace = $1  # We want to replace with first first 

    sub(pat,replace,line) # Do the substitution 
    pat=replace   # Next time the pattern to replace will have changed 

    if (NF==2)   # If the current line has 2 fields 
     print line,$1  # Print the line with the replacement and the 1st field 
    else     # Else 
     print line   # Just print the line with the replacement 
} 

要運行腳本,將它保存爲script.awk這樣的文件並運行awk -f script.awk file

+0

非常完美!謝謝!但是我仍然在學習awk,請問你要澄清一下嗎?我知道'{r = $ 2?$ 2:$ 1; sub(p,r,f); p = r; print $ 2?f「」$ 1:f}'是什麼,但是邏輯在這裏做了什麼:/[*]/{f = $ 0; p =「[*] +」; next}'@sudo_O – fembot 2013-04-22 19:59:27

+0

下一個問題:我可以在哪裏發送水果籃? ;-) 謝謝! – fembot 2013-04-22 20:07:42

+1

哈哈我的榮幸:)最好的方式來表示感謝它只是upvote。 – 2013-04-22 20:08:50