2010-04-08 87 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