Skip to content
Advertisement

Adding server hostname to each line of ‘find’ output

I am in need of a listing of all files with a specific extension on a server. I need it to show the server hostname, file size, and absolute path of the file.

echo $(hostname); find $(pwd) / -iname *.jpg -exec du -s {} ;

or

echo $(hostname); find $(pwd) / -iname *.jpg|xargs du -s

Almost get me there:
joes_server
5473 /home/joe/pics/sunset.jpg
8522 /home/joe/pics/mountains.jpg

I cannot figure out how to include the hostname on each line of the find output. My attempts to add the hostname function into the xargs or -exec section result in errors because it tries to apply hostname to the find’s output.

Is there a way to include the hostname on each line of the find output?

When looped through the many servers, I’d like to have an output like:
joes_server 5473 /home/joe/pics/sunset.jpg
joes_server 8522 /home/joe/pics/mountains.jpg
marys_server 5398 /home/mary/snapshots/background.jpg
janes_server 9642 /home/jane/pictures/flowers.jpg

Thanks

Advertisement

Answer

find "$PWD" / -iname '*.jpg' -exec du -s {} + | sed "s/^/$(hostname): /"

(But, as @chepner notes below, having both / and "$PWD" is redundant; a find from / will eventually visit your current working directory, so you can leave off the "$PWD". Or if you only want to look starting from where you are, just do find "$PWD" and leave off the /.)

Changes:

  1. Use $PWD instead of $(pwd) – no need to run a command when bash puts it in a parameter for you already

  2. QUOTE! QUOTE! QUOTE!

  3. Use + instead of ; on the find -exec so that it will pass more than one file to each invocation of du; it’s more efficient that way. If your version of find doesn’t support + here, you can use -print0 | xargs -0 du -s.

  4. Pipe the whole thing through sed to insert the hostname at the front of each line.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement