Zombo
Zombo

Reputation: 1

Print unique lines that also match pattern

Given this foo.txt

/bin/bar:
        KERNELBASE => /sbin/KERNELBASE (0x77670000)
        intl-8 => /usr/bin/intl-8 (0x6f970000)
        iconv-2 => /usr/bin/iconv-2 (0x6f980000)
        pcre-0 => /usr/bin/pcre-0 (0x6f780000)
        gcc_s-1 => /usr/bin/gcc_s-1 (0x6fdd0000)
/bin/baz:
        KERNELBASE => /sbin/KERNELBASE (0x77670000)
        intl-8 => /usr/bin/intl-8 (0x6f970000)
        iconv-2 => /usr/bin/iconv-2 (0x6f980000)

I would like this output

/usr/bin/intl-8
/usr/bin/iconv-2
/usr/bin/pcre-0
/usr/bin/gcc_s-1

That is to say, I would like to take unique lines containing /usr, then print the correct field. Currently I am using a pipe

grep /usr foo.txt | sort -u | cut -d' ' -f3

However could this be done with a oneline awk command? I came across this example

awk '!a[$0]++'

but I cannot see how to use this with only /usr lines.

Upvotes: 0

Views: 411

Answers (2)

Sidharth C. Nadhan
Sidharth C. Nadhan

Reputation: 2253

 awk '/\usr/ && ! a[$0]++{print $3}' foo.txt

Upvotes: 2

chthonicdaemon
chthonicdaemon

Reputation: 19770

The pattern matching in awk is one of its great advantages. Your example uses some shortcuts for simple cases, but an equivalent command to awk '!a[$0]++' is awk '($0 in a) {a[$0]; print}', which leads quite easily to adding an additional pattern. Also printing only the third field yields:

awk '/\/usr/ && !($0 in a) {a[$0]; print $3}'

Upvotes: 0

Related Questions