Reputation: 15920
How do I go about echoing only the filename of a file if I iterate a directory with a for loop?
for filename in /home/user/*
do
echo $filename
done;
will pull the full path with the file name. I just want the file name.
Upvotes: 126
Views: 262040
Reputation: 120644
Just use basename
:
echo `basename "$filename"`
The quotes are needed in case $filename
contains spaces.
Upvotes: 59
Reputation: 109
You can either use what SiegeX said above or if you aren't interested in learning/using parameter expansion, you can use:
for filename in $(ls /home/user/);
do
echo $filename
done;
Upvotes: 1
Reputation: 972
if you want filename only :
for file in /home/user/*; do
f=$(echo "${file##*/}");
filename=$(echo $f| cut -d'.' -f 1); #file has extension, it return only filename
echo $filename
done
for more information about cut
command see here.
Upvotes: 0
Reputation: 140327
If you want a native bash
solution
for file in /home/user/*; do
echo "${file##*/}"
done
The above uses Parameter Expansion which is native to the shell and does not require a call to an external binary such as basename
However, might I suggest just using find
find /home/user -type f -printf "%f\n"
Upvotes: 213
Reputation: 889
Another approach is to use ls
when reading the file list within a directory so as to give you what you want, i.e. "just the file name/s". As opposed to reading the full file path and then extracting the "file name" component in the body of the for loop.
Example below that follows your original:
for filename in $(ls /home/user/)
do
echo $filename
done;
If you are running the script in the same directory as the files, then it simply becomes:
for filename in $(ls)
do
echo $filename
done;
Upvotes: 12