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?
36 Answers
(cd /other/directory && ls)
Is there some reason why you can not use ls -1 ?
$ ls -1 /other/directory
file1
file2EDIT:
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
-1will list one file per line with just the file name (or path)- Using a wildcard and/or giving
lsa full path will output the full, absolute path for each file.basenamewill strip the path leaving you with just the file name.
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.
for i in `ls /some/directory` ;do basename $i;doneThe 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