Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To show only file name without the entire directory path

ls /home/user/new/*.txt prints all txt files in that directory. However it prints the output as follows:

[me@comp]$ ls /home/user/new/*.txt /home/user/new/file1.txt    /home/user/new/file2.txt    /home/user/new/file3.txt 

and so on.

I want to run the ls command not from the /home/user/new/ directory thus I have to give the full directory name, yet I want the output to be only as

[me@comp]$ ls /home/user/new/*.txt file1.txt    file2.txt    file3.txt  

I don't want the entire path. Only filename is needed. This issues has to be solved using ls command, as its output is meant for another program.

like image 483
Ashish Avatar asked Dec 15 '11 10:12

Ashish


People also ask

How do I show only file names in a directory?

/W - Displays only filenames and directory names (without the added information about each file) in a five-wide display format. dir c:*. This form of the DIR command will also display directories. They can be identified by the DIR label that follows the directory name.

How do I show only file names in Linux?

Normally find command will retrieve the filename and its path as one string. If you want to display only the filename, you can use basename command. find infa/bdm/server/source/path -type f -iname "source_fname_*. txt"

How do I separate filenames from path?

To get the file name from the path, use the os. path. basename() method. Working with UNIX or MacOS uses the slash / as path separator, and Windows uses the backslash \ as the separator.

How do I list only file names in Unix?

Linux or UNIX-like system use the ls command to list files and directories. However, ls does not have an option to list only directories. You can use combination of ls command, find command, and grep command to list directory names only. You can use the find command too.


1 Answers

ls whateveryouwant | xargs -n 1 basename

Does that work for you?

Otherwise you can (cd /the/directory && ls) (yes, parentheses intended)

like image 133
fge Avatar answered Sep 29 '22 06:09

fge