Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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.

like image 222
Anthony Miller Avatar asked Jan 25 '12 22:01

Anthony Miller


People also ask

How do I get only the ls filename?

If you want the ls command output to only contain file/directory names and their respective sizes, then you can do that using the -h option in combination with -l/-s command line option.

Why is it showing no file or directory?

The error "FileNotFoundError: [Errno 2] No such file or directory" is telling you that there is no file of that name in the working directory. So, try using the exact, or absolute path. In the above code, all of the information needed to locate the file is contained in the path string - absolute path.

How do I get only the filename in Linux?

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" Shell command to find the latest file name in the command task!


1 Answers

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" 
like image 115
SiegeX Avatar answered Oct 09 '22 01:10

SiegeX