Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting filename & modification time from ls output

I have a set of files in a directory. I want to extract just the filename without the absolute path & the modification timestamp from the ls output.

/apps/dir/file1.txt               
/apps/dir/file2.txt

now from the ls output i extract out the fields for filename & timestamp

ls -ltr /apps/dir | awk '{print $6 $7 $8 $9}'

Sep  25  2013 /apps/dir/file1.txt  
Dec  20  2013 /apps/dir/file2.txt  
Dec  20  2013 /apps/dir/file3.txt

whereas i want it to be like

Sep 25  2013 file1     
Dec 20  2013 file2  
Dec 20  2013 file3

one solution can be to cd to that directory and run the command from there, but is there a solution possible without cd? I also used substr() but since filenames are not of equal length so passing a constant value to substr() function didn't work out.

like image 390
Amiy Avatar asked Oct 17 '25 13:10

Amiy


2 Answers

With GNU find, you can do the following to get the filenames without path:

find /apps/dir -type f -printf "%f\n"

and as Kojiro mentioned in the comments, you can use %t or %T(format) to get modification time.

or do as BroSlow suggested

find /apps/dir -printf "%Ab %Ad %AY %f\n"

Do not try to do the following (It will break on filenames with spaces and even across different OS where ls -l representation has fewer/more columns:

ls -ltr /apps/dir | awk '{n=split($9,f,/\//);print $6,$7,$8,f[n]}'
like image 114
jaypal singh Avatar answered Oct 20 '25 05:10

jaypal singh


Dont parse output of ls command, rather use stat:

stat -c%y filename

This will print the last modification time in human readable format

Or if using GNU date you could use date with a format parameter and the reference flag

date '+%b %d %Y' -r filename

You can use basename to get just the filename portion of the path:

basename /path/to/filename

Or as Kojiro suggested with parameter expansion:

To get just the filename:

filename="${filename##*/}"

And then to strip of extension, if any:

filename="${filename%.*}"

Putting it all together:

#!/usr/bin/env bash

for filename in *; do
    timestamp=$(stat -c%y "$filename")
    #Uncomment below for a neater timestamp
    #timestamp="${timestamp%.*}"

    filename="${filename##*/}"
    filename="${filename%.*}"

    echo "$timestamp $filename"
done
like image 45
Timmah Avatar answered Oct 20 '25 04:10

Timmah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!