Is there a compact way to list files, with the host name prepended? My efforts to combine ls, xargs, paste and process substitution have failed me.

This is the best I came up with:

ls * | paste  <(echo $HOST)

Ultimately I want to list a bunch of files across multiple hosts by invoking a series of ssh commands so that I can do something like this:

ssh host1 "ls_with_hostname_prefix /var/log/*"
ssh host2 "ls_with_hostname_prefix /var/log/*"
ssh host3 "ls_with_hostname_prefix /var/log/*"

Related question on SO. You can simply do

ls | sed -e 's/^/$HOST /'

You probably want to store it as a script on the remote hosts or merge it even with the ssh:

function remote_ls_with_alias() {
  ssh $1 "ls $2 | sed -e \"s/^/$1 /\""

and run it as

remote_ls_with_alias host1 "/var/log/*"
remote_ls_with_alias host2 "/var/log/*"
remote_ls_with_alias host3 "/var/log/*"
| improve this answer | |
  • Man that's so obvious and I completely missed it, trying to be clever with the much less useful paste command. – Sridhar Sarnobat Dec 21 '16 at 22:32
  • Just a note to anyone else reading: Double quotes so hostname gets resolved. (I'd edit it myself but stack overflow says my edits are too short) – Sridhar Sarnobat Dec 21 '16 at 23:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.