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.
Solution 1:
ls whateveryouwant | xargs -n 1 basename
Does that work for you?
Otherwise you can (cd /the/directory && ls)
(yes, parentheses intended)
Solution 2:
No need for Xargs and all , ls is more than enough.
ls -1 *.txt
displays row wise
Solution 3:
There are several ways you can achieve this. One would be something like:
for filepath in /path/to/dir/*
do
filename=$(basename $filepath)
... whatever you want to do with the file here
done
Solution 4:
Use the basename
command:
basename /home/user/new/*.txt
Solution 5:
(cd dir && ls)
will only output filenames in dir. Use ls -1
if you want one per line.
(Changed ; to && as per Sactiw's comment).