Linux Shell - String manipulation then calculating age of file in minutes -


i writing script calculates age of oldest file in directory. first commands run are:

oldfile=`ls -lt $dir | grep "^-" | tail -1 `     echo $oldfile 

the output contains lot more filename. eg

-rwxrwxr-- 1 abc abc 334 may 10 2011 abcd_xyz20110510113817046.abc.bak 

q1/. how obtain output after last space of above line? give me filename. realise sort of string manipulation required new shell scripting.

q2/. how obtain age of file in minutes?

to obtain oldest file's name,

ls -lt | awk '/^-/{file=$nf}end{print file}' 

however, not robust if have files spaces in names, etc. generally, should try avoid parsing output ls.

with stat can obtain file's creation date in machine-readable format, expressed seconds since jan 1, 1970; date +%s can obtain current time in same format. subtract , divide 60. (more awk skills come in handy arithmetic.)

finally, alternate solution, @ options find; in particular, printf format strings allow extract file's age. following directly age in seconds , inode number of oldest file:

find . -maxdepth 1 -type f -printf '%t@ %i\n' | sort -n | head -n 1 

using inode number avoids issues of funny file names; once have single inode, converting file name snap:

find . -maxdepth 1 -inum "$number" 

tying 2 together, might want this:

# set -- replace $@ output command set -- $(find . -maxdepth 1 -type f -printf '%t@ %i\n' |          sort -n | head -n 1) # $1 timestamp , $2 inode  oldest_filename=$(find . -maxdepth 1 -inum "$2") age_in_minutes=$(date +%s | awk -v d="$1" '{ print ($1 - d) / 60 }') 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -