3

I need to locate a library on my system and it's name is expected to be found a couple of times. I want to keep only the first occurrence.

So far I've tried some methods for splitting strings by newlines but neither seem to work with locate's output.

I'm not using find because I don't know where the lib may be in advance.

Any other (better) way to handle this is also welcome.

1
  • Please add some of the output you're getting from locate. You can use commands such as grep & head to filter the output.
    – slm
    Commented Nov 21, 2013 at 19:23

2 Answers 2

3

There are several ways to filter the output from locate.

Method #1 - be explicit

If you know you're looking for a particular version of the library, then just ask locate for it directly.

$ locate libstdc++-3-libc6.2-2-2.10.0.so
/usr/lib/libstdc++-3-libc6.2-2-2.10.0.so

Method #2 - grep

If you're looking for glibc .so libraries then use grep to find only these results from locate.

$ locate libstdc++ | grep ".so$"
/usr/lib/libstdc++-3-libc6.2-2-2.10.0.so
/usr/lib/gcc/x86_64-redhat-linux/4.4.4/libstdc++.so
/usr/lib/gcc/x86_64-redhat-linux/4.4.4/32/libstdc++.so

Method #3 - only return the first 10 lines of the result

If you're more interested in finding the first results, then use head to return only the first few. You can direct head to return different numbers of results using the -# switch (shorter but non-standard equivalent of -n #):

Example

$ locate glibc | head -8
/usr/lib64/glib-2.0/include/glibconfig.h
/usr/sbin/glibc_post_upgrade.i686
/usr/sbin/glibc_post_upgrade.x86_64
/usr/share/aclocal/glibc2.m4
/usr/share/aclocal/glibc21.m4
/usr/share/doc/glibc-2.12
/usr/share/doc/glibc-common-2.12
/usr/share/doc/glibc-2.12/BUGS

(note that it returns 8 lines, that's not necessarily the same as file paths as file paths can be made of several lines since the newline character is as valid as any in a file name).

1
  • 2
    Head is the command I was looking for. I needed only the first one so I used head -1
    – tutuca
    Commented Nov 21, 2013 at 19:46
3

Some locate implementations like RedHat mlocate or GNU locate (the two most common ones on Linux-based operating systems) and most BSD's have a -l option for that:

locate -l1 mylib

If not, you're going to have to make the assumption that file names don't contain newline characters and pipe the output of locate to head -n 1 (some implementations of locate support a -0 option to delimit results with NUL characters instead of newline, but those also support -l anyway).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .