awk有条件地组合多行

时间:2011-08-15 17:28:36

标签: sed awk grep

如果匹配ID,我希望将来自不同长度的多行的值组合成一行。

输入示例是:

ID:  Value:
a-1  49
a-2  75
b-1  120
b-2  150
b-3  211
c-1  289
d-1  301
d-2  322

所需的输出示例是:

ID:  Value:
a 49,75
b 120,150,211
c 289
d 301,322

如何编写awk表达式(或sed或grep或其他内容)来检查ID是否匹配,然后将所有这些值打印到一行?我当然可以打印 将它们分成不同的列并稍后将它们组合起来,所以问题实际上只是有条件地打印,如果ID匹配,如果没有开始新的行。

5 个答案:

答案 0 :(得分:5)

在awk中,如果您的ID聚集在一起:

awk 'NR==1 {print $0}
NR > 1 {sub("-.*", "", $1)}
NR == 2 {prev=$1; printf "%s %s", $1, $2}
NR > 2 && prev == $1 {printf ",%s", $2}
NR > 2 && prev != $1 {prev=$1; printf "\n%s %s", $1, $2}' your_input_file

答案 1 :(得分:3)

鉴于您的意见:

awk '
  NR == 1 {print; next}
  {
    split($1,a,/-/)
    sep = values[a[1]] == "" ? "" : ","
    values[a[1]] = values[a[1]] sep $2
  }
  END {for (key in values) print key, values[key]}
'

产生

ID:  Value:
a 49,75
b 120,150,211
c 289
d 301,322

支持“列表哈希”的语言也很方便。这是一个Perl版本

perl -lne '
  if ($. == 1) {print; next}
  if (/^(.+?)-\S+\s+(.*)/) {
    push @{$values{$1}}, $2;
  }
  END {
    $, = " ";
    foreach $key (keys %values) {
    print $key, join(",", @{$values{$key}});
    }
  }
'

答案 2 :(得分:3)

在sed中,假设ID聚集在一起:

sed -n -e '1p;2{s/-.* / /;h};3,${H;x;s/\(.*\) \(.*\)\n\1-.* /\1 \2,/;/\n/{P;s/.*\n//;s/-.* / /};x};${x;p}' your_input_file

Bellow是一个注释的sed脚本文件,可以使用sed -n -f script your_input_file

运行
# Print the 1st line as is.
1p
# For the 2nd line, remove what is after - in the ID and save in the hold space.
2{s/-.* / /;h}
# For all the other lines...
3,${
# Append the line to the hold space and place it in the pattern space.
H;x
# Substitute identical ids by a ,.
s/\(.*\) \(.*\)\n\1-.* /\1 \2,/
# If we have a \n left in the pattern space, it is a new ID, so print the old and prepare the next.
/\n/{P;s/.*\n//;s/-.* / /}
# Save what remains in hold space for next line.
x}
# For the last line, print what is left in the hold space.
${x;p}

答案 3 :(得分:1)

给出input.txt文件中的输入:

awk '{split($1, a, "-"); hsh[a[1]]=hsh[a[1]]$2","}END{for (i in hsh){print i" "hsh[i]}}' input.txt | sed 's/,$//'

输出

a 49,75
b 120,150,211
c 289
d 301,322

答案 4 :(得分:0)

基于标准工具的解决方案,作为上述优秀解决方案的替代方案......

$ for INDEX in $(cut -f1 input | uniq); do echo -n "$INDEX  ";grep "^$INDEX" input | cut -f2 | tr '\n' ' ';echo; done
a  49 75 
b  120 150 211 
c  289 
d  301 322 

使用稍微修改过的输入,没有标题和索引,使用

创建
awk 'NR>1' input | sed 's/-[0-9]*//'
a       49
a       75
b       120
b       150
b       211
c       289
d       301
d       322