RSFalcon7
RSFalcon7

Reputation: 2311

Search in a file with awk

I need to search in a file like a hash. Wondering if awk is right solution

Input example:

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

I need two different outputs depending on the context:

Get keys:

bla ble bli blo

And search(ble)

www.ble.com

I was hoping that this is trivial with awk

Edit: Improved description for input format

Upvotes: 0

Views: 95

Answers (3)

Fredrik Pihl
Fredrik Pihl

Reputation: 45634

Not really clear about the format... How about this for a start?

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

or "two different outputs:

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

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

}

output:

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

Upvotes: 0

Kent
Kent

Reputation: 195029

get keys:

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

if you want them in one line with awk

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

Upvotes: 1

Guru
Guru

Reputation: 16974

One way like this(not very clear with requirement):

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

Upvotes: 1

Related Questions