使用awk在文件中搜索

时间:2013-01-18 12:20:53

标签: bash awk

我需要像哈希一样搜索文件。想知道awk是否是正确的解决方案

输入示例:

bla   123.123.123.0
# This line should be a comment
ble      www.ble.com
bli  <random whitespace> ::1
blo   anything

我需要两种不同的输出,具体取决于上下文:

获取密钥:

bla ble bli blo

搜索(ble)

www.ble.com

我希望awk

这是微不足道的

修改:改进了输入格式的说明

3 个答案:

答案 0 :(得分:1)

这样的一种方式(要求不是很清楚):

$ awk '!/^#/{a[$1]=$2}END{print a[x];}' x='ble' file
www.ble.com

答案 1 :(得分:1)

获取密钥:

kent$  grep -oP "^\w+(?= )" file
bla
ble
bli
blo

如果你想让它们与awk在一行中

kent$  awk 'NR!=2{printf $1" "}' test
bla ble bli blo 

答案 2 :(得分:0)

格式不太清楚......开始这个怎么样?

$ awk '/^[^#]/{print $1}/www/{print $2}' input.txt
bla
ble
www.ble.com
bli
blo

或“两种不同的输出:

/^[^#]/ {
    k[$1]++
}
/www/ {
    w[$2]++
}

END {
    print "keys:"
    for (x in k)
        print "\t"x
    print "urls:"
    for (x in w)
        print "\t"x

}

输出:

$ awk -f keys.awk input.txt
keys:
    bla
    ble
    bli
    blo
urls:
    www.ble.com