Run an ls without getting the full path

I want a simple list of files in a directory that is not my current directory. I run ls /other/directory/*.txt and get:

/other/directory/file1.txt
/other/directory/file2.txt

I want:

file1.txt
file2.txt

How can I get the second list?

3

6 Answers

(cd /other/directory && ls)

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)
1

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.
2

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.

18
for i in `ls /some/directory` ;do basename $i;done

The expression in `` gets expanded to the files, then each of them is passed to basename. Caveat: Does not work with files containing white spaces!

Try;

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like