Anthony Miller
Anthony Miller

Reputation: 15920

For files in directory, only echo filename (no path)

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

Answers (6)

Sean Bright
Sean Bright

Reputation: 120644

Just use basename:

echo `basename "$filename"`

The quotes are needed in case $filename contains spaces.

Upvotes: 59

Behzad
Behzad

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

josef
josef

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

SiegeX
SiegeX

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

ryan
ryan

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

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

Use basename:

echo $(basename /foo/bar/stuff)

Upvotes: 20

Related Questions