Copy newest file linux

Find files newer than a day and copy

I am working on a script that will copy ONLY files that have been created within the last day off to another folder. The issue I am having is the script I have copies all of the files in the source directory instead of just the files less than a day old. This is what I have:

find . -mtime -1 -exec cp --preserve --parents -a "<>" /somefolder \; 

The above code copies all of the files in the source directory. If I remove all of the arguments for ‘cp’ then it works:

find . -mtime -1 -exec cp "<>" /somefolder \; 

The above code copies only the newest files as I want but I need to preserve the attributes using the cp arguments. I have also tried variables and for loops thinking maybe the -exec option was the issue:

files="$(find -mtime -1)" for file in "$files" do cp --parents --preserve -a file /somefolder 

However, the above for loop results in the same issue, all files are copied. If I echo $files only the files I need are shown. How can I get this to work?

Ok I think I have it working using: find /sourcefolder -type f -mtime -1 -exec cp -a «<>» /somefolder \;

5 Answers 5

Some implementations of cp have a -t option, so you can put the target directory before the files:

find . -mtime -1 -exec cp -a --parents -t /somefolder "<>" \+ 

Note that -a implies —preserve so I removed the latter.

THanks everybody for the help, got it working using a combination of your suggestions:

went with the below code and it works perfectly.

find /sourcefolder -type f -mtime -1 -exec cp -a "<>" /somefolder \; 

You can use pax for this like:

pax -wrT "11$(date +%H%M)," . /destination/folder 
  • -wr — when pax is handed both -w rite and -r ead options it copies. Possibly also useful here. (but not included in the above command)
    • -l ink — which creates hard-links if at all possible rather than copying the file-data.
    • -X for restricting pax to the same source device and/or filesystem.
    • -s/src regex/replace/ — which modifies filenames in-stream
    • -v erbose — for reporting on files sourced/targeted.

    man pax

    • . Time comparisons using both file times is useful when pax is used to create a time based incremental archive (only files that were changed during a specified time range will be archived).
    • A time range is made up of six different fields and each field must contain two digits. The format is: [[[[[cc]yy]mm]dd]HH]MM[.SS]
    • Where cc is the first two digits of the year (the century), yy is the last two digits of the year, the first mm is the month (from 01 to 12), dd is the day of the month (from 01 to 31), HH is the hour of the day (from 00 to 23), MM is the minute (from 00 to 59), and SS is the seconds (from 00 to 59). The minute field MM is required, while the other fields are optional and must be added in the following order: HH, dd, mm, yy, cc
    • The SS field may be added independently of the other fields. Time ranges are relative to the current time, so. -T 1234/cm
    • . would select all files with a modification or inode change time of 12:34PM today or later.
    • Multiple -T time range can be supplied and checking stops with the first match.

    . so the 11 up there in my example command is relative to today — it is one less than today’s date — which is the twelfth — and the rest is just a standard «$(date)» format followed by a comma.

    . except — and the last thing worth mentioning — I use an absolute path for the target directory — and so should you if you do it. The docs all reference unspecified behavior for relative target paths — and the first time I ever tried using pax I was swearing under my breath for an hour in confusion with all of the weird results until I used an absolute path.

    Источник

    cp command in Linux/Unix

    cp is a Linux shell command to copy files and directories.

    cp command syntax

    Copy from source to dest

    $ cp [options] source dest

    cp command options

    option description
    cp -a archive files
    cp -f force copy by removing the destination file if needed
    cp -i interactive — ask before overwrite
    cp -l link files instead of copy
    cp -L follow symbolic links
    cp -n no file overwrite
    cp -R recursive copy (including hidden files)
    cp -u update — copy when source is newer than dest
    cp -v verbose — print informative messages

    cp command examples

    Copy single file main.c to destination directory bak:

    Copy 2 files main.c and def.h to destination absolute path directory /home/usr/rapid/ :

    $ cp main.c def.h /home/usr/rapid/

    Copy all C files in current directory to subdirectory bak :

    Copy directory src to absolute path directory /home/usr/rapid/ :

    Copy all files and directories in dev recursively to subdirectory bak:

    Interactive prompt before file overwrite:

    $ cp -i test.c bak
    cp: overwrite ‘bak/test.c’? y

    Update all files in current directory — copy only newer files to destination directory bak:

    cp code generator

    Select cp options and press the Generate Code button:

    See also

    Источник

    Copying newer files only

    I have a simple shell script. What i’d like to do, is copy the files in /home/imp/imp/msgs/ to /home/imp/imp/msgs/bak/ , but only if they are newer in the source directory than the destination directory.

    #!/bin/bash cp /home/imp/imp/msgs/*.MIX /home/imp/imp/msgs/bak/ cp /home/imp/imp/msgs/*.BRD /home/imp/imp/msgs/bak/ 

    3 Answers 3

    You can use rsync with the pattern *.MIX and *.BRD , e.g

    rsync -avm --include='*.MIX' --include='*.BRD' --exclude='*' /home/imp/imp/msgs/ /home/imp/imp/msgs/bak/ 

    You need to use cp -p to retain timestamps. Otherwise you can’t​ usefully compare them next time.

    cp -pu /home/imp/imp/msgs/*.MIX /home/imp/imp/msgs/bak/ cp -pu /home/imp/imp/msgs/*.BRD /home/imp/imp/msgs/bak/ 

    Make

    Here we generate Makefile dynamically using a heredoc and run the dynamic Makefile to accomplish the copy

    Bash

    SRCDIR="/home/imp/imp/msgs" for src in "$SRCDIR"/*.MIX "$SRCDIR"/*.BRD do dest=$/bak/$ if [ ! -e "$dest" ] || [ "$src" -nt "$dest" ] then /bin/cp -p "$src" "$dest" fi done 

    You must log in to answer this question.

    Hot Network Questions

    Subscribe to RSS

    To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

    Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.12.43529

    Linux is a registered trademark of Linus Torvalds. UNIX is a registered trademark of The Open Group.
    This site is not affiliated with Linus Torvalds or The Open Group in any way.

    By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

    Источник

    How to copy the top 10 most recent files from one directory to another?

    I want to move the newest 10 files to /home/thinkcode/Test I have this so far. Please correct me. I am looking for a one-liner!

    ls -lt *.htm | head -10 | awk '' | sh 

    You could use xargs and avoid awk + sh (feels ugly) or probably use find . -exec and run just one command.

    4 Answers 4

    ls -lt *.htm | head -10 | awk '' | sh 

    ls is notoriously bad about listing file names that have special characters in them. Also, parsing the output of ls -l is fraught with danger. Better to write a small perl script which will stat all of the files and sort the results by date. If you must use ls , at least leave off the -l argument. ls -t *.html | head -10 would work just as well.

    Does not work when there is spaces in file names. Use ls -t *.htm |head -10 |awk ‘‘ |sh` instead

    cp seems to understand back-ticked commands. So you could use a command like this one to copy the 10 latest files to another folder like e.g. /test :

    cp `ls -t *.htm | head -10` /test 

    Works great until you have a file with a space in its name, or even worse, a file named ; rm -fr —no-preserve-root / ; .htm in your folder.

    Here is a version which doesn’t use ls . It should be less vulnerable to strange characters in file names:

    find . -maxdepth 1 -type f -name '*.html' -print0 \| xargs -0 stat --printf "%Y\t%n\n" \| sort -n \| tail -n 10 \| cut -f 2 \| xargs cp -t ../Test/ 

    I used find for a couple of reasons:

    1) if there are too many files in a directory, bash will balk at the wildcard expansion*.

    2) Using the -print0 argument to find gets around the problem of bash expanding whitespace in a filename in to multiple tokens.

    * Actually, bash shares a memory buffer for its wildcard expansion and its environment variables, so it’s not strictly a function of the number of file names, but rather the total length of the file names and environment variables. Too many environment variables => no wildcard expansion.

    EDIT: Incorporated some of @glennjackman’s improvements. Kept the initial use of find to avoid the use of the wildcard expansion which might fail in a large directory.

    Источник

    Copying the newest files

    We have a script running which picks up the report generated monthly on remote servers. I was trying to find a way to pick up the latest file from the remote servers only. Will find work in script or that’s a bad practice?

    for host in "$"; do scp "$host":"$remote_path" "$local_target_dir"/filename."$host" done 

    2 Answers 2

    You can run a ls -rt via SSH on the server within the directory to find out the last modified file (based on its last modification date instead of the filename)

    fileToCopy=$(ssh "$host" "cd $remote_path && ls -rt | tail -1") scp "$host":"$remote_path"/"$fileToCopy" "$local_target_dir"/filename."$host" 

    surely you meant command substitution at fileToCopy=’ssh «$host$» «cd $remote_path» && ls -rt | tail -1″‘ ?

    I meant store the name of the file inside the variable fileToCopy and then use the filename in the script given in the question.

    Chirag, understood. But you are attempting to run ssh within single quotes, you must have meant back-quotes?

    @1_CR: You’re right. I tested the code in parts using double quotes, but forgot that it wouldn’t work in single quotes.

    I suggest to find it out validating your date and have in consideration the last backup, for example:

    #!/bin/bash day=$ last_month=$ if [ $day -eq 15] then echo "Is 15th, time to make get last backup!" scp -P port user@server:/dir/servername_BBC-3.0_$last_month* destination fi 

    You must log in to answer this question.

    Hot Network Questions

    Subscribe to RSS

    To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

    Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.12.43529

    Linux is a registered trademark of Linus Torvalds. UNIX is a registered trademark of The Open Group.
    This site is not affiliated with Linus Torvalds or The Open Group in any way.

    By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

    Источник

    Читайте также:  Booting linux on android
Оцените статью
Adblock
detector