List files by date added in terminal with function or script or another

bashcommand lineterminal

I found this in another post but would like to be able to call a script of function to reduce the amount of typing.

ls -a | \
grep -v '^\.$\|^\.\.$' | \
xargs -I {} mdls -name kMDItemFSName -name kMDItemDateAdded {} | \
sed 'N;s/\n//' | grep -v '(null)' | \
awk '{print $3 " " $4 " " substr($0,index($0,$7))}' | \
sort -r

This is the other post
Can I list files ordered by date added to a folder from a command-line tool like ls?

Best Answer

Simply create .bash_profile in your home folder or open it, if it already exists:

nano .bash_profile

and add the following lines:

function added {
    ls -a | grep -v '^\.$\|^\.\.$' | xargs -I {} mdls -name kMDItemFSName -name kMDItemDateAdded {} | sed 'N;s/\n//' | grep -v '(null)' | awk '{print $3 " " $4 " " substr($0,index($0,$7))}' | sort -r;
}

Save the mods with ctrl-o, Enter and quit nano with ctrl-x.

Close the Terminal window, open a new one and then simply enter added and you'll get the sorted list of files and folders in your home folder with some glitches though.

The accepted answer in the linked question presents a much faster solution:

function added2 {
    mdls -name kMDItemFSName -name kMDItemDateAdded -raw * | xargs -0 -I {} echo {} | sed 'N;s/\n/ /' | sort;
}