So say I have a list of files in a text file:


I have a script that will search through this text file and, much like the locate command, I want to be able to search for the basename of the file. Thus far I've used this grep command grep -E */.*${1}[^/]*$ which works fine UNLESS I want to grep for a regex. So, in the above example if I wanted to find files starting with "foo", I'd execute myscript --basename ^foo however this fails because the whole regex becomes grep -E */.*^foo[^/]*$ which would, obviously, fail. I thought about using xargs to plug each entry into basename but I need the script to put out the whole file path at the end.

Any ideas? I'd prefer POSIX compliance but GNUisms are fine too

  • 2
    Show your desired output for that sample input.
    – Cyrus
    Jun 19, 2015 at 17:46
  • I said files beginning with foo (in the basename) so: /bar/foo/ foobar /foobar/bar/ foo
    – user120161
    Jun 19, 2015 at 17:49
  • Well, sure, but are you not also looking for a way to pattern the pattern?
    – mikeserv
    Jun 19, 2015 at 17:57
  • Yes. In the above example, I don't want it to return "barfoo". This is one example though. I want to be able to apply any of the regex symbols to the basename of a file and return the wholename
    – user120161
    Jun 19, 2015 at 18:07

2 Answers 2


If foo must match at the start of the basename:

< inputfile grep '/foo[^/]*$'
  • /foo[^/]*$: matches a /foo string followed by any number of any character not / at the end of the string

if foo can match anywhere in the basename:

< inputfile grep 'foo[^/]*$'
  • foo[^/]*$: matches a foo string followed by any number of any character not / at the end of the string
  • 1
    It does also match it anywhere in the basename - like after stuff - but i think that's what is desired here.
    – mikeserv
    Jun 19, 2015 at 17:55
  • Wait no. In the above example it doesn't print the apropriate results.
    – user120161
    Jun 19, 2015 at 17:58
  • @mikeserv Good point, I made a distinction.
    – kos
    Jun 19, 2015 at 17:59
  • @mikeserv grep -e '/foo[^/]*$' -e '^foo[^/]*$'
    – Costas
    Jun 19, 2015 at 18:01
  • 1
    @user12061 Ok so stop using ^ and start using /foo
    – mikeserv
    Jun 19, 2015 at 18:06

If your grep supports PCRE (Perl-compatible regular expressions) :

$ grep -Po '.*/\Kfoo[^/]*$' file.txt 
  • .*/ will match upto the last / and \K will discard the match

  • foo[^/]*$ will find the filenames starting with foo

You must log in to answer this question.

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