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.
you could add an sed script to your commandline:
ls /home/user/new/*.txt | sed -r 's/^.+\///'
A fancy way to solve it is by using twice "rev" and "cut":
find ./ -name "*.txt" | rev | cut -d '/' -f1 | rev
When you want to list names in a path but they have different file extensions.
me@server:/var/backups$ ls -1 *.zip && ls -1 *.gz
Use the basename
command:
basename /home/user/new/*.txt
No need for Xargs and all , ls is more than enough.
ls -1 *.txt
displays row wise
(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).
just hoping to be helpful to someone as old problems seem to come back every now and again and I always find good tips here.
My problem was to list in a text file all the names of the "*.txt" files in a certain directory without path and without extension from a Datastage 7.5 sequence.
The solution we used is:
ls /home/user/new/*.txt | xargs -n 1 basename | cut -d '.' -f1 > name_list.txt
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
There are lots of way we can do that and simply you can try following.
ls /home/user/new | tr '\n' '\n' | grep .txt
Another method:
cd /home/user/new && ls *.txt
I prefer the base name which is already answered by fge. Another way is :
ls /home/user/new/*.txt|awk -F"/" '{print $NF}'
one more ugly way is :
ls /home/user/new/*.txt| perl -pe 's/\//\n/g'|tail -1
The selected answer did not work for me, as I had spaces, quotes and other strange characters in my filenames. To quote the input for basename
, you should use:
ls /path/to/my/directory | xargs -n1 -I{} basename "{}"
This is guaranteed to work, regardless of what the files are called.
Source: Stackoverflow.com