Run an ls without getting the full path

Solution 1:

(cd /other/directory && ls)

Solution 2:

Is there some reason why you can not use ls -1 ?

$ ls -1 /other/directory
file1
file2

EDIT:

I notice you've changed the question now - my solution won't work with your new example of ls /other/directory/*.txt. Use something like khachik's solution instead, e.g.

$ (cd /other/directory && ls -1 *.txt)

Solution 3:

ls -1 /other/directory/*.txt |xargs basename

  • -1 will list one file per line with just the file name (or path)
  • Using a wildcard and/or giving ls a full path will output the full, absolute path for each file. basename will strip the path leaving you with just the file name.

Solution 4:

1) I'm not sure this shouldn't be on superuser.com

2) ls doesn't print the full path anyway: ls -1 /your/dir

Edit The question has changed. Per Paul's comment below I am updating my answer. You can do it like this:

ls -1 /home/rich/*.txt | sed s/^.*\\/\//

That's a minus 1, not l, although l works too. Explanation: ls -l/-1 writes out the file names with the stuff you don't want. Each line is piped through sed, which here is doing a substitution, as specified by the s/. A substitution takes the form:

s/text/replacement/

We are substituting everything from the beginning of the line ^ upto the last / (/ is a special character so we have to escape it \\/) with nothing - i.e removing it, and thus leaving you with just the filename.