tristatemale
tristatemale

Reputation: 1

Shell - modifying the find command output

Is there anyway to print and output to a find command without listing the directory of the find in your output? meaning if I issue

find /home/people/name -type f -name >> /output/log/output.txt

the output in the log is written as:

/home/people/name/filename1.txt
/home/people/name/filename2.txt
/home/people/name/filename3.txt

what I want is the just the file name without the directory name? is that possible?

Upvotes: 0

Views: 628

Answers (1)

John1024
John1024

Reputation: 113864

By default, as you saw, find prints full paths:

$ find /home/people/name -type f
/home/people/name/filename1.txt
/home/people/name/filename3.txt
/home/people/name/filename2.txt

find, however, does offer control over the output using -printf. To get just the filename, with no path, try:

$ find /home/people/name -type f -printf '%f\n'
filename1.txt
filename3.txt
filename2.txt

%f tells find that you want the filename without the path. \n tells find that you want a newline after each filename.

The output can, of course, be saved in a file:

$ find /home/people/name -type f -printf '%f\n' >output.txt
$ cat output.txt
filename1.txt
filename3.txt
filename2.txt

MacOS & BSD

MacOS, which is derived from FreeBSD, does not support -printf. One solution on a Mac is to use gfind which can be installed via brew install findutils. Alternatively, @Lurker offered comment that suggests using: find /home/people/name -type f -exec basename {}.

Upvotes: 2

Related Questions