2015-09-27 47 views
0

我希望看到针对以下问题从您们那里收到不同类型的答案。我很好奇通过数组或任何其他匹配(如果有的话)完全解决了下面的问题。使用外壳进行密钥匹配

以下是问题所在。保留Name作为我们需要在一行中打印各种电话号码的关键。

$cat input.txt 

Name1, Phone1 
Name2, Phone2 
Name3, Phone1 
Name4, Phone5 
Name1, Phone2 
Name2, Phone1 
Name4, Phone1 

O/P: $猫output.txt的

Name1,Phone1,Phone2 
Name2,Phone2,Phone1 
Name3,Phone1 
Name4,Phone5,Phone1 

我解决了上述问题,但我希望看到解决的技术或许有比我更有效。我还不是初学者水平的专家。我下面的代码:

$cat keyMatchingfunction.sh 
while read LINE; do 
    var1=(echo "$LINE"|awk -F\, '{ print $1 }') 
    matching_line=(grep "$var1" output.txt|wc -l) 
    if [[ $matching_line -eq 0 ]]; then 
    echo "$LINE" >> output.txt 
    else 
    echo $LINE is already present in output.txt 
    grep -q -n "$var1" output.txt 
    line_no=(grep -n "$var1" output.txt|cut -d: -f1) 
    keymatching=(echo "$LINE"|awk -F\, '{ print $2 }') 
    sed -i "$line_no s/$/,$keymatching/" output.txt 
    fi 
done 
+2

你是怎么解决这个问题的? – hjpotter92

+1

通常的做法是将文件和管道排序为一个简单的Awk脚本,只要第一个字段保持不变,就会收集输入。 – tripleee

+0

@ hjpotter92:用代码编辑我的帖子..检查 – user3624000

回答

3

试试这个:

awk -F', ' '{a[$1]=a[$1]","$2}END{for(i in a) print i a[i]}' input.txt 

输出:

 
Name1,Phone1,Phone2 
Name2,Phone2,Phone1 
Name3,Phone1 
Name4,Phone5,Phone1 
+0

上述代码在'input.txt'文件中没有空格时如何进行修改.... – user3624000

+0

删除逗号后的空格。 – Cyrus

1

使用bash和排序:

#!/bin/bash 

declare -A array   # define associative array 

# read file input.txt to array 
while IFS=", " read -r line number; do 
    array["$line"]+=",$number" 
done < input.txt 

# print array 
for i in "${!array[@]}"; do 
    echo "$i${array[$i]}" 
done | sort 

输出:

 
Name1,Phone1,Phone2 
Name2,Phone2,Phone1 
Name3,Phone1 
Name4,Phone5,Phone1