Howto get only filename from find command in Linux?

Hi every body!

I would like to get only filename in the result of find command in Linux but I don't know howto. Tks so much for your helps.

The basename utility can convert long paths into the filename.

FILE="`basename /path/to/file`"
echo $FILE

Depending on your system or shell you may be able to convert it with shell builtins, which would be more efficient. What are they?

I write script from bash shell on Fedora14.

I have a function (plagiarized) which separates the directory, the filename, and the extension.

	function dir_file_ext ()
{
	for FILE in $(find . -name "*.*"); do
		BASENAME="${FILE%.[^.]*}"
		DIRNAME="${BASENAME%/[^/]*}"
		FILENAME="${BASENAME:${#DIRNAME} + 1}"
		EXT="${FILE##*\.}"
		echo "${DIRNAME}/${FILENAME}.${EXT}"
	done
	}

And the last echo statement can put them back together again!

It works even if there are multiple dots/periods '.' in the filename.

Enjoy!

ok tks so much. I got it!

Hi nguyendu0102,

You can use printf option within find command too, as follow:

find . -type f -ls -printf "filename --> %f\n"

Or without printing paths given by "ls" output :

find . -type f -printf "filename --> %f\n"

Or simply:

find . -type f -printf "%f\n"
  • find command as shown above will print only files ("-type f") in current folder and within its subfolders. If you only want
    to print files within current folder (not subfolders) you must add "- maxdepth 1" option after dot.
find . -maxdepth 1 -type f -printf "%f\n"

Hope it helps.

Regards.