2010-04-08 92 views
21

我有一個腳本,每次都會生成兩行輸出。我真的只是對第二行感興趣。此外,我只對在第二行的一對#之間出現的文字感興趣。此外,在哈希之間使用另一個分隔符:^ A。這將是巨大的,如果我也可以打破文字分開各部分即^ A分隔(注意,^ A是SOH特殊字符,並且可以使用Ctrl-A鍵打字)獲取第n行文本輸出

回答

6
your.program | tail +2 | cut -d# -f2 

應該讓你2/3的方式。

+1

切斷對由^分隔值的undeterminate量用最好的工具? – syker 2010-04-08 17:26:09

+1

我不確定。我不明白你的目標是以^ A的方式。把它們變成別的東西?換行符? – Grumdrig 2010-04-08 18:23:00

0

慶典:

read 
read line 
result="${line#*#}" 
result="${result%#*}" 
IFS=$'\001' read result -a <<< "$result" 

$result現在是一個包含你感興趣的只是管腳本的輸出到這一個元素的數組。

57
output | sed -n '1p' #prints the 1st line of output 

output | sed -n '1,3p' #prints the 1st, 2nd and 3rd line of output 
+2

你的回答比較好。不知道爲什麼另一個被接受。很混亂。 – Fuser97381 2014-08-12 13:50:18

+1

這正是我所期待的。謝謝! @ n-1-1你知道是否可以使用sed指定行1,3,5而不是1-5?我自己找不到任何東西。 – Olshansk 2016-06-19 01:32:56

1

我可能會使用awk。

your_script | awk -F# 'NR == 2 && NF == 3 { 
          num_tokens=split($2, tokens, "^A") 
          for (i = 1; i <= num_tokens; ++i) { 
           print tokens[i] 
          } 
          }' 

這是說

1. Set the field separator to # 
2. On lines that are the 2nd line, and also have 3 fields (text#text#text) 
3. Split the middle (2nd) field using "^A" as the delimiter into the array named tokens 
4. Print each token 

顯然,這使得很多的假設。例如,如果#或^ A可以合法地顯示在數據中,而不是分隔符,則可能需要對其進行調整。但是這樣的事情應該讓你開始。您可能需要使用nawk或gawk或其他東西,我不完全確定awk是否可以處理控制角色的分裂。

0

這裏是一個可能的解決方案的awk

awk -F"#" 'NR==2{ 
for(i=2;i<=NF;i+=2){ 
    split($i,a,"\001") # split on SOH 
    for(o in a) print o # print the splitted hash 
} 
}' file 
1

提高Grumdrig的回答是:

your.program | head -n 2| tail -1 | cut -d# -f2