Bash Script to Find and Display Oldest File

find oldest file from list


#!/bin/sh

while IFS= read -r file; do
[ "${file}" -ot "${oldest=$file}" ] && oldest=${file}
done < filelist.txt

echo "the oldest file is '${oldest}'"

Linux bash script to find and delete oldest file with special characters and whitespaces in a directory tree if condtion is met

If you really want to process files with spaces, new lines and any special characters, you must consider using a null \0 as the limit for file names, like this:

dir=/mnt/volume0/recordings

find "$dir"/ -type f -printf '%T+ %p\0' |
sort -zk1,1 |
head -n1 -z |
cut -zd ' ' -f2- |
xargs -0 echo rm -f --

This will find files in a dir and forcefully will remove the oldest file (only one) (if the echo is removed, test it before actually using it).

unix find oldest file in directory by date in filename

Try this:

ls -1 | sed 's/^\([^0-9]*\)\([0-9]\+\.txt\)/\2\1/g' | sort -n | head -1 | sed 's/^\([0-9]\+\.txt\)\(.*\)/\2\1/g'

This command do next:

  1. Print files list in current directory
  2. Move prefixes in file names in the end of file names
  3. Sort files numerically (as file names are started from timestamps now)
  4. Leaves only file with oldest timestamp.
  5. Moves prefixes back.

Though timestamps in file names look a bit strange: you already have timestamp in file inode, which you can see using stat command, so why using additional timestamps in file names? I can see only one case for this: if file modifying time was changed artificially (e.g. with touch command).

Write shell script to move oldest file in the directory to the new directory.?

You can use below command to move the oldest file into some other directory :

mv $(ls -t /home/balaji/work| tail -1) /home/balaji/regular_archieve/

ls -t: This command will list all file in the directory sorted by modification time, newest first.

tail -1: It will pick the last file which will be the oldest one.

How to get oldest file in ftp directory using bash script

Finally this script Works for me: lftp -u user,password -e "cls --sort=date; quit" ftpserveraddress/Folder 2> /dev/null | tail -n 1

How do I print oldest file and include its timestamp from a directory via UNIX


ls -ltr | head -1 |  awk '{OFS="\t"} {print $6, $7, $8, $9}'

awk's print statement takes an index,

If the output of your ls -ltr is

-rw-r--r-- 1 abc abc 185 Dec 19 11:23 testfile.csv

then

 $6: date (19)
$7: month (Dec)
$8: time (11:23)
$9: file name (testfile.csv)

index starts with 1 from left to right.

Note: https://www.gnu.org/s/gawk/manual/gawk.html awk is crazy powerful.

bash to select oldest folder in directory and write to log

Your idea of using find is right, but with a little tweaking like this

$ IFS= read -r -d $'\0' line < <(find . -maxdepth 1 -type d -printf '%T@ %p\0' \ 
2>/dev/null | sort -z -n)

$ printf "The oldest directory: %s\n" "${line#* }"

Similar to the one answered here.



Related Topics



Leave a reply



Submit