I'm trying to create a macro for Keyboard Maestro for OS X doing the following:
- Get name of newest file in a directory on my disk based on date created;
- Paste the text "newest file: " plus the name of the newest file.
One of its options is to "Execute a shell script", so I thought that would do it for 1. After Googling around a bit I came up with this:
cd /path/to/directory/
ls -t | head -n1
This sorts it right, and returns the first filename. However, it also seems to includes a line break, which I do not want. As for 2: I can output the text "newest file: " with a different action in the app, and paste the filename behind that. But I'm wondering if you can't return "random text" + the outcome of the ls
command.
So my question is: can I do this only using the ls
command? And how do I get just the name of the latest file without any linebreaks or returns?
If you want, you can add more text on the end in the same way.
Since you're already using pipes, just throw another one in there:
(Note that the "printf" does not include a '\n' at the end; that gets rid of the linebreak)
Edit:
With Arkku's suggestion to exit awk after the first line, it looks like:
Since this comes up first when I search for "find newest file on mac shell" then I thought I would post for others to help...
If you are trying to find the file in just that directory ls is good, but I found that find works quite well, and you might learn something new in the process. I however had to get the GNU find on my mac in order to use the line of code that diimdeep posted above.
If you run Homebrew, which you should if you spend any time in terminal, or maybe one of the alternatives. You can run "brew install findutils" Once this is finished the code from above will work like this...
Just change the last bit to a 10 if you want more. gfine will take a path if you need to specify that as well. I usually cd into the folder that I want to start in though. Find is automatically recursive.
Using output of
ls
is bad practice.find -type f -printf '%T+ %p\n' | sort -r | head -n 1
You can't do it with only
ls
. However, asecho
is generally built into the shell, it doesn't really add any overhead into the script. To get just the name of the file, I'd suggest:If, for some reason, you really want to eliminate the
head
, then I suppose you could go for something like:(
read
is built into the shell,head
isn't.)Note that these solutions do not recurse into subdirectories, since that was not specified in the question. In fact, subdirectories may be printed as the newest "file".
You can do that in bash in a single statement like so:
You can also remove that newline without
echo
:Make sure
ls
doesn't output colors to non-tty streams (i.e. specify color byls --color=never
orls --color=auto
or not at all).The
ls
solution will output files of any kind sorted by modification time. If you want only regular files or if you don't want directories then you can usefind
andxargs
: