Score:0

How to Automate a job to move the latest file with a sequential file name

bw flag

I have files in a directory all part of a sequential naming structure. I want to automate a job where I can find the latest file in this sequence and copy it over to another directory.

E.g. in /tmp/directory23 there are file names:

CEN_01 [Modified date 31/05/2021]
CEN_02 [Modified date 07/06/2021]
CEN_03 [Modified date 14/06/2021]
CEN_04 [Modified date 21/06/2021]
CEN_05 [Modified date 28/06/2021]
CEN_06 [Modified date 05/07/2021]

I want to automate a job, where I find the latest modified file CEN_06 and copy the file to a different directory.

Can anyone help me please?

FedKad avatar
cn flag
Look at `man ls`. The command sequence `last_file=$(ls -t | head -n1)` will assign the file name you need into a shell variable.
Score:1
lb flag

There's two parts in your question, so I'll adress them separately. I also don't know how confortable your are with Linux, so please tell me if these guidelines are too blurry.

  • find the latest modified file CEN_06 and copy the file to a different directory : you should be able to do that using the output of ls -lt, and then grabbing the first result. After some search, the following seems to be working : ls -t | head -n1 (edit: thanks to @FedonKadifeli for this command). To copy a file, the cp command is what you are looking for.
  • I want to automate a job : one way to automate stuff in Linux is to use crontabs. You should be able to do what you want using them. I recommand you read the man on that subject man 5 crontab. You basically put in a .sh file the commands you want to run, and then crontab will automate it for you at given intervals.
FedKad avatar
cn flag
Why are you using this very long command sequence, while a simple `ls -t | head -n1` could easily do the job?
uz flag
Jos
@FedonKadifeli Even better, because Malo's command tends to print an extra space at the start of the file name.
hr flag
... or use `zsh`, where you don't need to rely on fragile parsing of ls output and instead can use a qualified shell glob like `CEN_*(om[1])`
Malo Maisonneuve avatar
lb flag
@FedonKadifeli Thanks! This is a lot better. I'll update my far too long command :)
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.