I have a directory with these files:

app_conf.jboss.app_hostname_20160913_191141.tgz app_conf.jboss.app_hostname_20160913_194047.tgz app_conf.provider.app_hostname_20160913_194044.tgz app_conf.provider.app_hostname_20160928_071002.tgz app_conf.deployments.ear.app_hostname_20160913_194047.tgz app_conf.deployments.ear.app_hostname_20160915_071005.tgz app_conf.bin.jboss_cluster.app_hostname_20160913_194044.tgz app_conf.bin.jboss_cluster.app_hostname_20160913_194047.tgz app_conf.bin.conf.app_hostname_20160913_194043.tgz app_conf.bin.conf.app_hostname_20160913_194047.tgz

The files are varying only by date because could be exists multiple files with the same part of the name ("string_name"_YYMMDD_HHMMSS.tgz)

I need a script that only copy the last version of the file depending your type.




It shoul copy only string_name1_20160913_194047.tgz.

And do this for all the rest type of files...

For Now I'm copying manually:

scp username@host:/tmp/string_name1_20160913_194047.tgz /home/config/

Appreciate any input on this.

1 Answer 1


With zsh:

cd /home/config && ssh user@host << \EOF | tar xpf -
zsh -c '
  cd /tmp || exit
  typeset -A seen; files=()
  for f (app_conf*_*_*.tgz(On)) {let '\''seen[${f%_*_*}]++'\'' || files+=($f)}
  tar cf - $files'

If user's login shell on host is zsh, you can simplify it to:

cd /home/config && ssh user@host '
  cd /tmp || exit
  typeset -A seen; files=()
  for f (app_conf*_*_*.tgz(On)) {let '\''seen[${f%_*_*}]++'\'' || files+=($f)}
  tar cf - $files' | tar xpf -

The idea is that we process the list of files in reverse order ((On)) and select the file if the part of the file name before _*_* has not been seen.

The files are transferred using tar which also has the benefit of transferring all the files' meta-data.

(see How to use associative arrays safely inside arithmetic expressions? for why we're using let instead of ((...)) here).

  • Hi Stéphane, Im searching and testing with zsh. Interesting!!.. Thanks..
    – j.lab
    Commented Oct 1, 2016 at 3:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .