使用shell进行密钥匹配 [英] Key Matching using shell

查看:93
本文介绍了使用shell进行密钥匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望看到你们针对以下问题收到的不同类型的答案.我很好奇,下面的问题可以通过数组或其他任何匹配项(如果有)完全解决.

I wanted to see different type of answers I receive from you guys for the below problem. I am curious to see below problem being solved completely through array or any other matching (if there is any).

下面是问题所在.保持Name为键,我们需要在一行中打印其各个电话号码.

Below is the problem. Keeping Name as the key we need to print their various phone numbers in a line.

$cat input.txt

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

O/P: $ cat output.txt

O/P: $cat output.txt

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

我解决了以上问题,但我想看看一种解决方法,也许比我更有效.我仍然不是shell的专家,但仍处于初学者水平.我的代码如下:

I solved the above problem but I wanted to see a solving technique perhaps one that is more effective than me. I am not an expert in shell still at a beginner level. My code below:

$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

推荐答案

尝试一下:

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

这篇关于使用shell进行密钥匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆